Swift is a powerful and intuitive programming language for Apple platforms and beyond.

Posts under Swift tag

200 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

otential Optimization or Bug in UINavigationController Push Operation in iOS 18
Issue Description: In iOS 18, when setting the root view controller of a UINavigationController and immediately pushing another view controller, the root view controller's lifecycle methods, such as viewDidLoad(), are not called as expected. This issue does not occur in previous iOS versions. There is no mention of this behavior in the iOS 18 release notes, and it is causing significant issues in our application. Steps to Reproduce: Set the root view controller of a UINavigationController. Immediately push another view controller. Observe that the root view controller's lifecycle methods, such as viewDidLoad(), are not called. Example Code: Swift import UIKit class HomeViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() print("HomeViewController viewDidLoad") } } class SecondViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() print("SecondViewController viewDidLoad") } } @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { window = UIWindow(frame: UIScreen.main.bounds) let home = HomeViewController() let rootNav = UINavigationController(rootViewController: home) window?.rootViewController = rootNav window?.makeKeyAndVisible() let secondViewController = SecondViewController() home.navigationController?.pushViewController(secondViewController, animated: true) return true } } Expected Behavior: The root view controller's lifecycle methods, such as viewDidLoad(), should be called when setting it as the root view controller of a UINavigationController. Actual Behavior: In iOS 18, the root view controller's lifecycle methods are not called when it is set as the root view controller and another view controller is immediately pushed. Impact: This issue affects the proper initialization and setup of the root view controller, causing significant disruptions in our application's workflow. Device Information: iOS Version: iOS 18 Test Devices: iPhone 15, iPhone 16 Additional Information: We would appreciate any insights or updates on whether this is an intended optimization or a potential bug. This issue is causing significant disruption to our application, and a timely resolution would be greatly appreciated.
3
0
427
Dec ’24
Animatable AnyInsettableShape
System provides AnyShape type erasure that animates correctly. But system doesn't provide AnyInsettableShape. Here is my implementation of AnyInsettableShape (and AnyAnimatableData that is needed to support animation). Let me know if there is simpler solution. struct AnyInsettableShape: InsettableShape { private let _path: (CGRect) -> Path private let _inset: (CGFloat) -> AnyInsettableShape private let _getAnimatableData: () -> AnyAnimatableData private let _setAnimatableData: (_ data: AnyAnimatableData) -> AnyInsettableShape init<S>(_ shape: S) where S : InsettableShape { _path = { shape.path(in: $0) } _inset = { AnyInsettableShape(shape.inset(by: $0)) } _getAnimatableData = { AnyAnimatableData(shape.animatableData) } _setAnimatableData = { data in guard let otherData = data.rawValue as? S.AnimatableData else { assertionFailure(); return AnyInsettableShape(shape) } var shape = shape shape.animatableData = otherData return AnyInsettableShape(shape) } } var animatableData: AnyAnimatableData { get { _getAnimatableData() } set { self = _setAnimatableData(newValue) } } func path(in rect: CGRect) -> Path { _path(rect) } func inset(by amount: CGFloat) -> some InsettableShape { _inset(amount) } } struct AnyAnimatableData : VectorArithmetic { init<T : VectorArithmetic>(_ value: T) { self.init(optional: value) } private init<T : VectorArithmetic>(optional value: T?) { rawValue = value _scaleBy = { factor in (value != nil) ? AnyAnimatableData(value!.scaled(by: factor)) : .zero } _add = { other in AnyAnimatableData(value! + (other.rawValue as! T)) } _subtract = { other in AnyAnimatableData(value! - (other.rawValue as! T)) } _equal = { other in value! == (other.rawValue as! T) } _magnitudeSquared = { (value != nil) ? value!.magnitudeSquared : .zero } _zero = { AnyAnimatableData(T.zero) } } fileprivate let rawValue: (any VectorArithmetic)? private let _scaleBy: (_: Double) -> AnyAnimatableData private let _add: (_ other: AnyAnimatableData) -> AnyAnimatableData private let _subtract: (_ other: AnyAnimatableData) -> AnyAnimatableData private let _equal: (_ other: AnyAnimatableData) -> Bool private let _magnitudeSquared: () -> Double private let _zero: () -> AnyAnimatableData mutating func scale(by rhs: Double) { self = _scaleBy(rhs) } var magnitudeSquared: Double { _magnitudeSquared() } static let zero = AnyAnimatableData(optional: nil as Double?) @inline(__always) private var isZero: Bool { rawValue == nil } static func + (lhs: AnyAnimatableData, rhs: AnyAnimatableData) -> AnyAnimatableData { guard let (lhs, rhs) = fillZeroTypes(lhs, rhs) else { return .zero } return lhs._add(rhs) } static func - (lhs: AnyAnimatableData, rhs: AnyAnimatableData) -> AnyAnimatableData { guard let (lhs, rhs) = fillZeroTypes(lhs, rhs) else { return .zero } return lhs._subtract(rhs) } static func == (lhs: AnyAnimatableData, rhs: AnyAnimatableData) -> Bool { guard let (lhs, rhs) = fillZeroTypes(lhs, rhs) else { return true } return lhs._equal(rhs) } @inline(__always) private static func fillZeroTypes(_ lhs: AnyAnimatableData, _ rhs: AnyAnimatableData) -> (AnyAnimatableData, AnyAnimatableData)? { switch (!lhs.isZero, !rhs.isZero) { case (true, true): (lhs, rhs) case (true, false): (lhs, lhs._zero()) case (false, true): (rhs._zero(), rhs) case (false, false): nil } } }
0
0
419
Dec ’24
WatchConnectivity Swift 6 - Incorrect actor executor assumption
I am trying to migrate a WatchConnectivity App to Swift6 and I found an Issue with my replyHandler callback for sendMessageData. I am wrapping sendMessageData in withCheckedThrowingContinuation, so that I can await the response of the reply. I then update a Main Actor ObservableObject that keeps track of the count of connections that have not replied yet, before returning the data using continuation.resume. ... @preconcurrency import WatchConnectivity actor ConnectivityManager: NSObject, WCSessionDelegate { private var session: WCSession = .default private let connectivityMetaInfoManager: ConnectivityMetaInfoManager ... private func sendMessageData(_ data: Data) async throws -> Data? { Logger.shared.debug("called on Thread \(Thread.current)") await connectivityMetaInfoManager.increaseOpenSendConnectionsCount() return try await withCheckedThrowingContinuation({ continuation in self.session.sendMessageData( data, replyHandler: { data in Task { await self.connectivityMetaInfoManager .decreaseOpenSendConnectionsCount() } continuation.resume(returning: data) }, errorHandler: { (error) in Task { await self.connectivityMetaInfoManager .decreaseOpenSendConnectionsCount() } continuation.resume(throwing: error) } ) }) } Calling sendMessageData somehow causing the app to crash and display the debug message: Incorrect actor executor assumption. The code runs on swift 5 with SWIFT_STRICT_CONCURRENCY = complete. However when I switch to swift 6 the code crashes. I rebuilt a simple version of the App. Adding bit by bit until I was able to cause the crash. See Broken App Awaiting sendMessageData and wrapping it in a task and adding the @Sendable attribute to continuation, solve the crash. See Fixed App But I do not understand why yet. Is this intended behaviour? Should the compiler warn you about this? Is it a WatchConnectivity issue? I initially posted on forums.swift.org, but was told to repost here.
3
0
1.1k
Jan ’25
App Settings Not Appearing with Xcode 16.2
I recently encountered an issue with Xcode 16.2 while attempting to integrate Settings.bundle into a new app. I added Settings.bundle as a new file (using the provided template), but when I ran the app (the default "Hello World" project), the expected three default controls (Name, Enabled, Slider) did not appear in the app's settings. To troubleshoot, I downgraded my system to macOS Sonoma 14.7.2 and Xcode 15.4 (on a 2023 Mac Mini, M2). After this downgrade, everything worked as expected. With a new project, adding Settings.bundle, and running the app, the settings entry for the app appeared, including the three default fields. This behavior suggests a potential issue or incompatibility with Xcode 16.2.
3
3
1.3k
Dec ’24
The app icon is not appearing under the "From Apps on Your iPhone" section in Apple Wallet.
Hello, We are integrating Apple Wallet functionality using the Thales SDK. While we’ve successfully implemented In-App provisioning, we are encountering an issue with the Wallet Extension. I followed the documentation provided here to implement the Apple Wallet Extension: https://developer.dbp.thalescloud.io/docs/d1-developer-portal/ab10ea4059dx1-apple-wallet-extension I’ve implemented everything as per the guide, but I’m still unable to see my app logo in the Wallet Extension under "From Apps on Your iPhone." Could anyone help identify what might be missing or point me in the right direction to resolve this issue. Thanks!
0
0
435
Dec ’24
Is it possible to Add Reply of Push Notification from Airpod using Voice ?
We want to do below addition to iOS Mobile App. Airpod announces Push notification = which is workking now we want to use voice command that "Reply to this" and sending Reply to that notification but it is saying it is not supported in your app. So basically we need to use feature - Listen and respond to messages with AirPods Do we need to add any integration inside app for this or it will directly worked with Siri settings ? Is it possible to do in non messaging App? Is it possible to do without syncing contacts ?
0
0
474
Dec ’24
Need clarification on using Apple MapKit in CarPlay
I have developed a mobile app using SwiftUI that supports GoogleMaps. Now I am in the process of building a CarPlay application. I assume CarPlay only supports Apple MapKit, as I could not find any way to integrate the Google Maps. Below are few queries, Could you please guide me on how I can obtain the user's current location on the CarPlay app launch? Is there a way CarPlay can get the details from the mobile app(not pretty sure as its using Google Maps)? If the user is logged out from the mobile app, what is the flow in CarPlay? Do we have any standard login page asking user to login to the mobile app first? Is there any UI asking the user to capture the location in CarPlay? This is my first CarPlay app. Kindly guide me to a document or so that covers these details. Thanks a ton!!
1
0
440
Jan ’25
Background Location Indicator Remains Active Despite "Never" Permission Setting in iOS 18+
Hi everyone, I'm encountering an issue where the background location indicator remains visible on the status bar even though I have set the location permissions to Never for my app in the system settings. Despite taking all the necessary steps to stop location tracking (including stopping updates, geofencing, and other location-related services), the indicator still appears. This seems to be a bug since everything has been turned off on my end. Here’s what I’ve already tried: Setting location permissions to Never in the settings. Stopping startUpdatingLocation(), stopMonitoringSignificantLocationChanges(), and geofencing (using locationManager.stopMonitoringRegions()). Calling locationManager.showsBackgroundLocationIndicator = false. Ensuring that the CLLocationManager is fully invalidated. Despite all of this, the background location indicator still remains in the status bar. I’ve tested it on real devices, as well as in the simulator, with no improvement. Has anyone experienced something similar, or can suggest why this might be happening? Could this be related to an iOS 18+ issue? Any insights or guidance would be greatly appreciated.
0
0
343
Dec ’24
Whats the Appkit equivalent of SwiftUI's NavigationSplitView?
How do I implement the same Navigation split view with a side bar in Appkit? Basically I have this code: import SwiftUI struct ContentView: View { var body: some View { NavigationSplitView { // Sidebar List { NavigationLink("Item 1", value: "Item 1 Details") NavigationLink("Item 2", value: "Item 2 Details") NavigationLink("Item 3", value: "Item 3 Details") } .navigationTitle("Items") } content: { // Main content (detail view for selected item) Text("Select an item to see details.") .padding() } detail: { // Detail view (for the selected item) Text("Select an item from the sidebar to view details.") .padding() } } } struct MyApp: App { var body: some Scene { WindowGroup { ContentView() } } } and wanted to somehow convert it to Appkit. I tried to use an NSSplitViewController but I still don't have that side bar and that button to collapse it, how do I go about this?
2
0
617
Dec ’24
Seeking Help - Need to Identify Date Contacts Were Added
Saw this info: https://developer.apple.com/documentation/contacts/cncontactstore But have no idea what I'm doing. This is a pressing matter and I need to determine the date/time contacts were originally created on my icloud account. I have tried the shortcuts method and it merely shows the date they were loaded into whichever device i'm logged in on if they were created a while ago
0
0
373
Dec ’24
How to combine contextMenu & RoundedRectangle?
I am trying to create a list of not rectangular elements, each of which has a context menu. However, I am encountering an issue with the corners when performing a long press. What is the correct way to use such a combination? I don't want to use List because of its default styling. The issue takes place only while animation is in progress. Here's a simplified code example that can be copied pasted and ran in one file. The video was recorded on the device with iOS 18.2 import SwiftUI @main struct MyApp: App { var body: some Scene { WindowGroup { TestView() } } } struct TestView: View { let items = ["Item 1", "Item 2", "Item 3"] var body: some View { VStack { ForEach(items, id: \.self) { item in HStack { Text(item) Spacer() Image(systemName: "star") } .padding() .background(.yellow) // tried all these in different combinations, none works .contentShape(RoundedRectangle(cornerRadius: 10)) .clipShape(RoundedRectangle(cornerRadius: 10)) .containerShape(RoundedRectangle(cornerRadius: 10)) .contextMenu { Button { print("Edit \(item)") } label: { Text("Edit"); Image(systemName: "pencil") } } } } .padding() } } #Preview { TestView() }
1
0
334
Dec ’24
UIViewController.view.backgroundColor auto changed when present
This is easy to reproduce,in dark mode, 2 UIViewControllers A and B, A present B. code: class AAA: UIViewController { override func viewDidLoad() { super.viewDidLoad() navigationItem.title = "AAA" view.backgroundColor = .systemBackground } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { present(UINavigationController(rootViewController: BBB()), animated: true) } } class BBB: UIViewController { override func viewDidLoad() { super.viewDidLoad() navigationItem.title = "BBB" view.backgroundColor = .systemBackground } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { dismiss(animated: true) } } before present: after present: Obviously, the backgroundColor of the view has changed. I guess it's because view's backgroundColor is the same as the the window, so changed the color to distinguish between the controller and the background, but this brought unexpected changes which is confusing. I want to know how this happened and how I can manually control it
1
0
272
Jan ’25
How to Digitally Sign a PDF File in Swift?
I'm currently working on a project in Swift where I need to digitally sign a PDF file. I have the following resources available: Private Key stored in the iOS Keychain with a tag. Public Key also stored in the iOS Keychain with a tag. A valid certificate stored as a PEM string. I need to digitally sign a PDF file with the above keys and certificate, but I'm struggling to find a clear and straightforward example or guidance on how to achieve this in Swift. Specifically, I’m looking for help with: Creating the digital signature using the private key and certificate. Embedding this signature into the PDF file. Any considerations I should be aware of regarding the format of the signed PDF (e.g., CMS, PKCS7, etc.). If anyone has experience with digitally signing PDFs in Swift, I would greatly appreciate your guidance or code examples. Thank you in advance!
0
0
503
Dec ’24
FirstResponderView/FirstResponderIndexPath in TableView
I found when I put a webView on the screen and then remove it, several properties in TableView including firstResponderView, FirstResponderIndexPath, and FirstResponderViewType have changed. These properties are hidden and I cannot change them. firstResponderView strong holds my cell, resulting in my cell not being able to call didEndDisplayCell when it slides out of the screen as expected. What should I do to avoid firstResponderView from strong holding my cell, or what should I do to release it?
1
0
358
Dec ’24
Using AsyncStream vs @Observable macro in SwiftUI (AVCam Sample Code)
I want to understand the utility of using AsyncStream when iOS 17 introduced @Observable macro where we can directly observe changes in the value of any variable in the model(& observation tracking can happen even outside SwiftUI view). So if I am observing a continuous stream of values, such as download progress of a file using AsyncStream in a SwiftUI view, the same can be observed in the same SwiftUI view using onChange(of:initial) of download progress (stored as a property in model object). I am looking for benefits, drawbacks, & limitations of both approaches. Specifically, my question is with regards to AVCam sample code by Apple where they observe few states as follows. This is done in CameraModel class which is attached to SwiftUI view. // MARK: - Internal state observations // Set up camera's state observations. private func observeState() { Task { // Await new thumbnails that the media library generates when saving a file. for await thumbnail in mediaLibrary.thumbnails.compactMap({ $0 }) { self.thumbnail = thumbnail } } Task { // Await new capture activity values from the capture service. for await activity in await captureService.$captureActivity.values { if activity.willCapture { // Flash the screen to indicate capture is starting. flashScreen() } else { // Forward the activity to the UI. captureActivity = activity } } } Task { // Await updates to the capabilities that the capture service advertises. for await capabilities in await captureService.$captureCapabilities.values { isHDRVideoSupported = capabilities.isHDRSupported cameraState.isVideoHDRSupported = capabilities.isHDRSupported } } Task { // Await updates to a person's interaction with the Camera Control HUD. for await isShowingFullscreenControls in await captureService.$isShowingFullscreenControls.values { withAnimation { // Prefer showing a minimized UI when capture controls enter a fullscreen appearance. prefersMinimizedUI = isShowingFullscreenControls } } } } If we see the structure CaptureCapabilities, it is a small structure with two Bool members. These changes could have been directly observed by a SwiftUI view. I wonder if there is a specific advantage or reason to use AsyncStream here & continuously iterate over changes in a for loop. /// A structure that represents the capture capabilities of `CaptureService` in /// its current configuration. struct CaptureCapabilities { let isLivePhotoCaptureSupported: Bool let isHDRSupported: Bool init(isLivePhotoCaptureSupported: Bool = false, isHDRSupported: Bool = false) { self.isLivePhotoCaptureSupported = isLivePhotoCaptureSupported self.isHDRSupported = isHDRSupported } static let unknown = CaptureCapabilities() }
0
0
348
Dec ’24
traitCollectionDidChange iOS18
iOS18.2 / iPhone 16pro / Xcode 16.2 'traitCollectionDidChange' This function has been deprecated since ios17. However, in ios18, when I changed the app to the background state or changed it to the foreground state again, it was confirmed that the function worked. It hasn't been confirmed in ios17, but why is it only confirmed in ios18?
0
0
601
Dec ’24