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

Posts under Swift tag

201 Posts

Post

Replies

Boosts

Views

Activity

Programming Languages Resources
This topic area is about the programming languages themselves, not about any specific API or tool. If you have an API question, go to the top level and look for a subtopic for that API. If you have a question about Apple developer tools, start in the Developer Tools & Services topic. For Swift questions: If your question is about the SwiftUI framework, start in UI Frameworks > SwiftUI. If your question is specific to the Swift Playground app, ask over in Developer Tools & Services > Swift Playground If you’re interested in the Swift open source effort — that includes the evolution of the language, the open source tools and libraries, and Swift on non-Apple platforms — check out Swift Forums If your question is about the Swift language, that’s on topic for Programming Languages > Swift, but you might have more luck asking it in Swift Forums > Using Swift. General: Forums topic: Programming Languages Swift: Forums subtopic: Programming Languages > Swift Forums tags: Swift Developer > Swift website Swift Programming Language website The Swift Programming Language documentation Swift Forums website, and specifically Swift Forums > Using Swift Swift Package Index website Concurrency Resources, which covers Swift concurrency How to think properly about binding memory Swift Forums thread Other: Forums subtopic: Programming Languages > Generic Forums tags: Objective-C Programming with Objective-C archived documentation Objective-C Runtime documentation Share and Enjoy — Quinn “The Eskimo!” @ Developer Technical Support @ Apple let myEmail = "eskimo" + "1" + "@" + "apple.com"
0
0
1.9k
Oct ’25
Having trouble with RawRespresentable "Expected to decode String but found a dictionary instead."
I want to use AppStorage for a custom struct I am using struct Activities { var name: String var age: Int } struct ContentView: View { @AppStorage("key") private var activities: Activities = .init(name: "Albert", age: 42) var body: some View { VStack { TextField("Activity Name", text: $activities.name) } } } The above code generates a compiler warning, recommending I add RawRepresentable conformance. So I've added it like this: extension Activities: RawRepresentable { public init?(rawValue: String) { guard let data = rawValue.data(using: .utf8) else { return nil } do { let result = try JSONDecoder().decode(Activities.self, from: data) self = result } catch { print(error) return nil } } var rawValue: String { guard let data = try? JSONEncoder().encode(self), let result = String(data: data, encoding: .utf8) else { return "{}" } return result } } This leads to a stack overflow because calling encode from rawValue calls rawValue. :-( I overcame this by declaring Codable conformance and overriding the default Encodable implementation: extension Activities: Codable { enum CodingKeys: String, CodingKey { case name case age } func encode(to encoder: any Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(name, forKey: .name) try container.encode(age, forKey: .age) } } This solves the stack overflow, but now init?(rawValue: String) is failing and I'm not sure why. When I set a breakpoint in my catch block I see the following: (lldb) po error ▿ DecodingError ▿ typeMismatch : 2 elements - .0 : Swift.String ▿ .1 : Context - codingPath : 0 elements - debugDescription : "Expected to decode String but found a dictionary instead." - underlyingError : nil (lldb) po rawValue {"name":"Albert2","age":42} (lldb) po data ▿ 27 bytes - count : 27 ▿ bytes : 27 elements - 0 : 123 - 1 : 34 - 2 : 110 - 3 : 97 - 4 : 109 - 5 : 101 - 6 : 34 - 7 : 58 - 8 : 34 (truncated to save space for posting :-)
2
0
328
1d
NSURLSession background downloadTasks sometimes calling urlSession(_:downloadTask:didFinishDownloadingTo:) *twice*
I've just implemented background session downloads, and in testing (with 1044 downloadTasks), I'm seeing some strange behavior that's not 100% reproducible. Sometimes when I background the app, when I foreground it (or the OS does), the URLSessionDownloadDelegate's function urlSession(_:downloadTask:didFinishDownloadingTo:) gets called twice. I'm also logging the URLSessionTaskDelegate's function urlSession(_:task:didCompleteWithError:) and in this case, it does not get called between calls to didFinishDownloadingTo. Both cases are being called with the exactly same task, session and location. The first call copies the location to a semi-permanent destination (and I confirmed that file is correct), and the second call fails on move because the destination already exists. I can obviously work around this fairly easily, but wondering if I'm missing something or if there's a bug. It does appear to happen more reliably when I background for 15 seconds or longer. A second issue which is reproducible is that while backgrounded, some files are completing downloads and never calling the download delegate's urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:) I tried resuming one or all of the tasks in applicationDidBecomeActive as suggested in multiple other forums posts, but neither of those seems to resolve the issue. Again, I can work around this (using a combination of totalBytesWritten and the known size of files which have completed downloads), but I'm wondering if I'm missing something obvious. I actually thought that perhaps the resume() workaround was causing the first issue, but removing it does not have an effect.
8
0
2.0k
1d
App Store Review Crash but no Crash Log
Hello, I've been trying the last week trying to get my app approved for the App Store. It's my first app and I'm not really sure what's going on. My app is getting rejected due to "App Completeness". Here's the rejection message: App Review Guideline Issue This is an automated message. The review of this submission cannot proceed. See below for more information. The app crashed after the initial launch. Apps that crash negatively impact users. Test the app on supported devices to identify and resolve crashes and stability issues before resubmitting for review. Learn more about testing a release build. When we submitted the first time we got rejected because our Apple sign in did not auto fill the user's name and we didn't have the EULA Link in the description. So the app didn't crash here as a tester sent screenshots and was in our app. We resubmitted and then we started getting these crashes. I examined the code we added from the first revision and tested the start up and everything worked fine on ours and our 30+ beta testers end. The thing is we're not getting a crash log from Apple testers or Apple's automated tester (if automated testing exists?). We are creating a fitness app that implements HealthKit. We have the required HealthShare and HealthUpdate messages in the signing and capabilities of our target. I'm not sure this would be the issue since the app actually executed the first run though. I've researched and some articles did say long load times on bad internet could make iOS terminate an app. So we worked to get our initial load network calls down from 10 seconds to about 1-2 seconds. This did not work either. We are using SwiftData to cache exercises fetched from our backend locally but we haven't made any changes to the entity's. So I wouldn't expect bad data to cause a crash especially because we flush even if it were bad data anyway. I've ran with instruments to see if this was a memory issue: With an Authed User with data loaded it gets to about 33MiB With a fresh install memory usage is about 17MiB I did have a point of interest in my profile: api.revenuecat.com is not listed in your app’s NSPrivacyTrackingDomain key in any privacy manifest. It may be following users across multiple apps and websites to create a profile about users of apps that contact this domain. I don't use revenue cat for tracking for Ads so I probably shouldn't add it to the NSPrivacyTrackingDomain right? I'm really lost here any advice would be much appreciated. I guess my questions are if Apple has an automating testing environment how can I closely match that for testing on my end? If this is an actual tester why am I not getting a crash log or steps to repeat this issue? Has anyone else experienced the pain I'm currently suffering?
0
0
179
1d
Custom keyboard extension left edge detecting touch after a second.
I'm creating a custom keyboard extension. So as a result, there are buttons which are pinned to the left edge of the keyboard. (Think of q key as an example). The logic of the key presses go something like this: Button detects a touchDown event and shows the magnified text which you normally see in system keyboard when tapping a key. Button detects a touchUpInside/touchDragOutside event and the magnified text disappears, again very similar to the system keyboard. This logic worked for all the buttons which were not pinned to the left edge of the keyboard. But for the buttons that were pinned to the left edge, the touchDown events were being detected after a second. So you can see this is obviously bad because I want to see the magnified text right after I place my finger on the button. WHAT I TRIED AS AN ALTERNATIVE: I removed all the touchDown, touchUpInside and touchDragOutside events from the button and disabled all their user interaction. Then I implemented to touches functions(touchesBegan, touchesEnded, etc.) and observed the touch locations on the background view. Surprisingly, even in this case, the touchesBegan function was called after a second after I placed my finger on the left edge of the screen and as usual, the touchesBegan function called just fine in the rest of the screen. Here's the code for the touches function: override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { 		guard let touch = event?.allTouches?.first else { return } 		let location = touch.location(in: self.touchView) 				 		print(location) } What exactly is happening here? And what can I do to avoid this problem? NOTE: It works fine in simulator for some reason but has a problem with real devices.
1
2
554
2d
Issues with my APN tokens
Hey guys, I made a app that features push notificaions, and I keep having problems setting them up. It asks permissions, and then it says that it cannot get the APN token after 10 seconds, and I am positive that I have enabled Push Notificaions in the provisioning profile in Xcode. Can anyone help me fix this issue?
1
0
847
3d
deduplicated_symbol error
HI, I have a Swift UI app in the mac appstore in the upcoming release we have made lots of changes and it is working fine in debug mode but in production with testflight or direct distribution we are getting the following crash while working in the app. this is happening in the rendering phase. Thread 0 Crashed:: Dispatch queue: com.apple.main-thread 0 libswiftCore.dylib 0x19546f270 swift_unknownObjectRetain + 44 1 libswiftCore.dylib 0x1954bb09c swift_cvw_initWithCopyImpl(swift::OpaqueValue*, swift::OpaqueValue*, swift::TargetMetadata<swift::InProcess> const*) + 280 2 libswiftCore.dylib 0x1958f685c initializeWithCopy for ClosedRange<>.Index + 212 3 VirtualProg 0x104d73958 <deduplicated_symbol> + 56 How can i debug to find out what is causing the issue and fix it?. thanks in advance
2
0
98
4d
Live Activity / Dynamic Island countdown responds to manual device clock changes, while app timer and shielding remain correct
Our app runs offline-first focus sessions using FamilyControls / ManagedSettings shielding and DeviceActivity monitoring. The in-app session timer is protected against wall-clock manipulation by using monotonic elapsed time, and the shield remains active correctly when the user manually changes the iPhone clock. However, the Live Activity and Dynamic Island countdown appear to use the device's wall clock for their timer rendering. If the user changes the device time from Settings during an active session, the Live Activity / Dynamic Island countdown immediately jumps forward or backwards, even though the underlying session has not changed. Is there a recommended ActivityKit approach for rendering a Live Activity / Dynamic Island countdown that is resistant to manual device clock changes? If not, is this an expected limitation of Live Activity timer rendering? And is there any supported way for the host app or widget extension to detect wall-clock manipulation so the Live Activity can be corrected, dismissed, or replaced with a safer non-countdown state?
0
0
82
4d
String Catalogs auto-generated symbols located in Swift Packages with default Main Actor isolation don't compile with Xcode 26.4
Hello, I've already reported this issue via Feedback Assistant a month ago (FB22340897) but it's still open and I'd like to know whether I can expect something to be changed regarding it. Here are the details: It seems that Xcode 26.4 started specifying nonisolated for the resourceBundleDescription in the generated stringSymbols files for Swift packages: from: private let resourceBundleDescription = LocalizedStringResource.BundleDescription.atURL(resourceBundle.bundleURL) to: private nonisolated let resourceBundleDescription = LocalizedStringResource.BundleDescription.atURL(resourceBundle.bundleURL) This causes a compilation error: Main actor-isolated default value in a nonisolated context when the Package.swift for the Swift Package in which the string catalog is located specifies: swiftSettings: [.defaultIsolation(MainActor.self)] Since all tools (String Catalogs, Swift Packages and default actor isolation to be Main Actor) are recommended by Apple, I believe it should be possible to use all these together like before Xcode 26.4.
1
0
698
5d
Bundle preferred languages mechanism
Hi there, I’m curious to understand how the system determines which language to use for an app. The system is currently set to en-IN (English - India). My app supports the following languages: en (the default development language) en-GB (United Kingdom) en-IE (Ireland) en-US (United States) When I run the app, the Bundle.main.preferredLanguages returns [„en-GB“, „en“], which causes the app to be set to en-GB. However, when the app doesn’t support the preferred system language, I would expect it to default to the en language. Surprisingly, this is not the case. This behavior is precisely described in Technical Note TN2418. Unfortunately, there’s no explanation provided. Is this behavior related to the CLDR Linguistic Distance? I also attempted to replace the default development language en with en-001 (English - world), but it had no effect.
3
0
149
1w
How to detect if a binding is from a state or a constant?
Hi, I'm trying to create a custom TextField component where we can have our own custom FormatStyle as a param and then it will change the value binding according to the FormatStyle. It worked with State<Any?> like for example $textValue. But when I use .constant(2000) for instance, the Formatting doesn't work. So is there any way to detect whether the value param is constant or not? Thank you.
0
0
80
1w
macOS main.swift and Main actor-isolated conformance cannot be used in nonisolated context
For a simple, resourceless cocoa apps I used to manually setup the application lifecycle (mimicking what's documented here: https://developer.apple.com/documentation/appkit/nsapplication), so my main.swift would look like: import Cocoa let delegate = SomeDelegate() _ = NSApplication.shared NSApp.delegate = delegate NSApp.run() This triggers a warning in Xcode 26.2: "Main actor-isolated conformance of SomeDelegate cannot be used in nonisolated context; this is an error in Swift 6 language mode". so what is the recommended way to refactor above so that it is Swift 6 compliant?
1
0
709
1w
Storefront.current?.countryCode returns inconsistent values in TestFlight builds
Hi, We're experiencing inconsistent and unexpected values returned by Storefront.current?.countryCode when running our app via TestFlight. In our case: The device region and locale are set to Poland The App Store account (Media & Purchases) is also set to Poland However, when running a TestFlight build, Storefront.current?.countryCode sometimes returns a completely different value (e.g. "NO" for Norway), which does not match the current App Store account configuration. Here's the code we're using: if #available(iOS 15.0, *) { let code = await Storefront.current?.countryCode print("Storefront countryCode:", code ?? "nil") } What's particularly confusing: Across different devices logged into the same App Store account, we sometimes receive different countryCode values The returned value does not seem to reflect the current App Store region or device settings We understand that Storefront reflects the App Store storefront and not the device locale, but in this case the value appears stale or incorrect even with a properly configured App Store account. Questions: Is Storefront.current?.countryCode expected to behave differently in TestFlight vs. production builds? Are there known caching or propagation delays for storefront updates across devices? Can TestFlight builds return outdated or inconsistent storefront values? What is the recommended way to reliably determine the user's App Store region in this scenario? We rely on storefront to determine regional availability of features, so understanding this behavior is important for us. Thanks in advance for any clarification!
1
0
94
1w
Understanding '.waiting' state in NWConnection.State for UDP
While going through the documentation for NWConnection, there seems to be state known as .waiting which means that the connection is waiting for a path change. For TCP, the state is understandable and can occur under some scenarios. But for the case of UDP, I have following queries: Why do we need .waiting state for the case of UDP? Even if we do need .waiting state for UDP, when all does this state occurs?
3
0
172
1w
AppStore.sync() not restoring purchases
On an app that was using the old API for In-App Purchases (StoreKit 1). The app is already published on the App Store. The purchase is non-consumable. While trying to migrate to StoreKit 2, I'm unable to restore purchases. Specifically displaying and purchasing products works as expected, but when deleting and reinstalling the app, and then trying to restore purchases I can't do it. I'm trying to restore them using the new APIs but it doesn't seem to be working. What I have tried so far: I'm listening for transaction updates during the whole lifetime of the app, with: Task.detached { for await result in Transaction.updates { if case let .verified(safe) = result { } } } I have a button that calls this method, but other than prompting to log in again with the Apple ID it doesn't seem to have any effect at all: try? await AppStore.sync() This doesn't return any item for await result in Transaction.currentEntitlements { if case let .verified(transaction) = result { } } This doesn't return any item for await result in Transaction.all { if case let .verified(transaction) = result { } } As mentioned before I'm trying this after purchasing the item and deleting the app. So I'm sure it should be able to restore the purchase. Am trying this both with a Configuration.storekit file on the simulator, and without it on a real device, in the Sandbox Environment. Has anyone being able to restore purchases using StoreKit 2? PD: I already filed a feedback report on Feedback Assistant, but so far the only thing that they have replied is: Because StoreKit Testing in Xcode is a local environment, and the data is tied to the app, when you delete the app you're also deleting all the transaction data for that app in the Xcode environment. The code snippets provided are correct usage of the API. So yes, using a Configuration.storekit file won't work on restoring purchases, but if I can't restore them on the Sandbox Environment I'm afraid that this won't work once released, leaving my users totally unable to restore what they have already purchased.
3
0
1.9k
1w
SwiftUI View Not Initialized on Background Relaunch (CoreBluetooth / Cold Start?)
I have a question regarding cold start and pre-warming behavior on iOS. I’m developing a SwiftUI app that continuously receives data from a BLE device in the background. We’ve observed that after the BLE stream stops, the OS often terminates our app. Later, when the sensor comes back into range, iOS appears to relaunch (or reinitialize) the app. In our app, we use a WindowGroup like this: WindowGroup { AppView(store: store) } We’ve placed our BLE reconnection logic inside a .task modifier in AppView. What’s confusing is this: Most of the time, when the app is relaunched, AppView is created and the .task runs as expected. However, in about 1 out of 10 cases, AppView is not created at all, so the .task does not execute. I’m trying to understand: Under what conditions does iOS relaunch an app without fully initializing the SwiftUI view hierarchy? Is this related to pre-warming or background relaunch mechanisms (e.g., CoreBluetooth state restoration)? What determines whether the WindowGroup and root view are actually instantiated? Any insight into the system’s relaunch behavior or lifecycle in this scenario would be greatly appreciated.
2
0
146
1w
SCNTechnique clearColor Always Shows sceneBackground When Passes Share Depth Buffer
Problem Description I'm encountering an issue with SCNTechnique where the clearColor setting is being ignored when multiple passes share the same depth buffer. The clear color always appears as the scene background, regardless of what value I set. The minimal project for reproducing the issue: https://www.dropbox.com/scl/fi/30mx06xunh75wgl3t4sbd/SCNTechniqueCustomSymbols.zip?rlkey=yuehjtk7xh2pmdbetv2r8t2lx&st=b9uobpkp&dl=0 Problem Details In my SCNTechnique configuration, I have two passes that need to share the same depth buffer for proper occlusion handling: "passes": [ "box1_pass": [ "draw": "DRAW_SCENE", "includeCategoryMask": 1, "colorStates": [ "clear": true, "clearColor": "0 0 0 0" // Expecting transparent black ], "depthStates": [ "clear": true, "enableWrite": true ], "outputs": [ "depth": "box1_depth", "color": "box1_color" ], ], "box2_pass": [ "draw": "DRAW_SCENE", "includeCategoryMask": 2, "colorStates": [ "clear": true, "clearColor": "0 0 0 0" // Also expecting transparent black ], "depthStates": [ "clear": false, "enableWrite": false ], "outputs": [ "depth": "box1_depth", // Sharing the same depth buffer "color": "box2_color", ], ], "final_quad": [ "draw": "DRAW_QUAD", "metalVertexShader": "myVertexShader", "metalFragmentShader": "myFragmentShader", "inputs": [ "box1_color": "box1_color", "box2_color": "box2_color", ], "outputs": [ "color": "COLOR" ] ] ] And the metal shader used to display box1_color and box2_color with splitting: fragment half4 myFragmentShader(VertexOut in [[stage_in]], texture2d<half, access::sample> box1_color [[texture(0)]], texture2d<half, access::sample> box2_color [[texture(1)]]) { half4 color1 = box1_color.sample(s, in.texcoord); half4 color2 = box2_color.sample(s, in.texcoord); if (in.texcoord.x < 0.5) { return color1; } return color2; }; Expected Behavior Both passes should clear their color targets to transparent black (0, 0, 0, 0) The depth buffer should be shared between passes for proper occlusion Actual Behavior Both box1_color and box2_color targets contain the scene background instead of being cleared to transparent (see attached image) This happens even when I explicitly set clearColor: "0 0 0 0" for both passes Setting scene.background.contents = UIColor.clear makes the clearColor work as expected, but I need to keep the scene background for other purposes What I've Tried Setting different clearColor values - all are ignored when sharing depth buffer Using DRAW_NODE instead of DRAW_SCENE - didn't solve the issue Creating a separate pass to capture the background - the background still appears in the other passes Various combinations of clear flags and render orders Environment iOS/macOS, running with "My Mac (Designed for iPad)" Xcode 16.2 Question Is this a known limitation of SceneKit when passes share a depth buffer? Is there a workaround to achieve truly transparent clear colors while maintaining a shared depth buffer for occlusion testing? The core issue seems to be that SceneKit automatically renders the scene background in every DRAW_SCENE pass when a shared depth buffer is detected, overriding any clearColor settings. Any insights or workarounds would be greatly appreciated. Thank you!
1
0
719
2w
NEURLFilter Not Blocking urls
Hi I tried to follow this guide https://developer.apple.com/documentation/networkextension/filtering-traffic-by-url I downloaded the sample app and put our pir service server address in the app. The service is already running and the app is connected to the pir service but the url is still not blocked. We tried to block example.com. Is there anything that we need to do in iOS code? This is the sample when there's dataset This is the sample when there's no dataset
1
0
98
2w
iOS crash: EXC_BAD_ACCESS in iOS 26+ when mouting/dismounting WebView
I'm experiencing a native crash on iOS 26+ with WebKit with title: EXC_BAD_ACCESS (KERN_INVALID_ADDRESS). The stack trace points to UIKit/WebKit animation and context menu handling, and the crash occurs while a WebView is presented or dismissed. Crashed: com.apple.main-thread 0 WebKit 0x7bcfac <redacted> + 12 1 WebKit 0xaf5c34 <redacted> + 84 2 UIKitCore 0x34ebdc -[_UIContextMenuAnimator performAllCompletions] + 248 3 UIKitCore 0x7f997c block_destroy_helper.72 + 1840 4 UIKitCore 0x7fb4b4 objectdestroy.36Tm + 88 5 UIKitCore 0x7ad354 objectdestroy.3Tm + 30500 6 UIKitCore 0x5c0e5c __swift_memcpy192_8 + 4352 7 UIKitCore 0x21944 block_copy_helper.374 + 40 8 UIKitCore 0x1dc174 -[_UIGroupCompletion _performAllCompletions] + 160 9 UIKitCore 0x35d0c4 -[_UIGravityWellEffectBody .cxx_destruct] + 180 10 UIKitCore 0x215018 -[UIScrollView _contentLayoutGuideIfExists] + 72 11 UIKitCore 0x943e4 NSStringFromUIEdgeInsets + 304 12 UIKitCore 0x94348 NSStringFromUIEdgeInsets + 148 13 UIKitCore 0x8f598 __UIVIEW_IS_EXECUTING_ANIMATION_COMPLETION_BLOCK__ + 36 14 UIKitCore 0x1995d8c -[UIViewAnimationBlockDelegate _sendDeferredCompletion:] + 92 15 libdispatch.dylib 0x1adc _dispatch_call_block_and_release + 32 16 libdispatch.dylib 0x1b7fc _dispatch_client_callout + 16 17 libdispatch.dylib 0x38b10 _dispatch_main_queue_drain.cold.5 + 812 18 libdispatch.dylib 0x10ec8 _dispatch_main_queue_drain + 180 19 libdispatch.dylib 0x10e04 _dispatch_main_queue_callback_4CF + 44 20 CoreFoundation 0x6a2b4 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 16 21 CoreFoundation 0x1db3c __CFRunLoopRun + 1944 22 CoreFoundation 0x1ca6c _CFRunLoopRunSpecificWithOptions + 532 23 GraphicsServices 0x1498 GSEventRunModal + 120 24 UIKitCore 0x9ddf8 -[UIApplication _run] + 792 25 UIKitCore 0x46e54 UIApplicationMain + 336 26 - 0xedf88 main + 24 (AppDelegate.swift:24) 27 ??? 0x196686e28 (Missing)
0
0
102
2w
Programming Languages Resources
This topic area is about the programming languages themselves, not about any specific API or tool. If you have an API question, go to the top level and look for a subtopic for that API. If you have a question about Apple developer tools, start in the Developer Tools & Services topic. For Swift questions: If your question is about the SwiftUI framework, start in UI Frameworks > SwiftUI. If your question is specific to the Swift Playground app, ask over in Developer Tools & Services > Swift Playground If you’re interested in the Swift open source effort — that includes the evolution of the language, the open source tools and libraries, and Swift on non-Apple platforms — check out Swift Forums If your question is about the Swift language, that’s on topic for Programming Languages > Swift, but you might have more luck asking it in Swift Forums > Using Swift. General: Forums topic: Programming Languages Swift: Forums subtopic: Programming Languages > Swift Forums tags: Swift Developer > Swift website Swift Programming Language website The Swift Programming Language documentation Swift Forums website, and specifically Swift Forums > Using Swift Swift Package Index website Concurrency Resources, which covers Swift concurrency How to think properly about binding memory Swift Forums thread Other: Forums subtopic: Programming Languages > Generic Forums tags: Objective-C Programming with Objective-C archived documentation Objective-C Runtime documentation Share and Enjoy — Quinn “The Eskimo!” @ Developer Technical Support @ Apple let myEmail = "eskimo" + "1" + "@" + "apple.com"
Replies
0
Boosts
0
Views
1.9k
Activity
Oct ’25
Having trouble with RawRespresentable "Expected to decode String but found a dictionary instead."
I want to use AppStorage for a custom struct I am using struct Activities { var name: String var age: Int } struct ContentView: View { @AppStorage("key") private var activities: Activities = .init(name: "Albert", age: 42) var body: some View { VStack { TextField("Activity Name", text: $activities.name) } } } The above code generates a compiler warning, recommending I add RawRepresentable conformance. So I've added it like this: extension Activities: RawRepresentable { public init?(rawValue: String) { guard let data = rawValue.data(using: .utf8) else { return nil } do { let result = try JSONDecoder().decode(Activities.self, from: data) self = result } catch { print(error) return nil } } var rawValue: String { guard let data = try? JSONEncoder().encode(self), let result = String(data: data, encoding: .utf8) else { return "{}" } return result } } This leads to a stack overflow because calling encode from rawValue calls rawValue. :-( I overcame this by declaring Codable conformance and overriding the default Encodable implementation: extension Activities: Codable { enum CodingKeys: String, CodingKey { case name case age } func encode(to encoder: any Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(name, forKey: .name) try container.encode(age, forKey: .age) } } This solves the stack overflow, but now init?(rawValue: String) is failing and I'm not sure why. When I set a breakpoint in my catch block I see the following: (lldb) po error ▿ DecodingError ▿ typeMismatch : 2 elements - .0 : Swift.String ▿ .1 : Context - codingPath : 0 elements - debugDescription : "Expected to decode String but found a dictionary instead." - underlyingError : nil (lldb) po rawValue {"name":"Albert2","age":42} (lldb) po data ▿ 27 bytes - count : 27 ▿ bytes : 27 elements - 0 : 123 - 1 : 34 - 2 : 110 - 3 : 97 - 4 : 109 - 5 : 101 - 6 : 34 - 7 : 58 - 8 : 34 (truncated to save space for posting :-)
Replies
2
Boosts
0
Views
328
Activity
1d
NSURLSession background downloadTasks sometimes calling urlSession(_:downloadTask:didFinishDownloadingTo:) *twice*
I've just implemented background session downloads, and in testing (with 1044 downloadTasks), I'm seeing some strange behavior that's not 100% reproducible. Sometimes when I background the app, when I foreground it (or the OS does), the URLSessionDownloadDelegate's function urlSession(_:downloadTask:didFinishDownloadingTo:) gets called twice. I'm also logging the URLSessionTaskDelegate's function urlSession(_:task:didCompleteWithError:) and in this case, it does not get called between calls to didFinishDownloadingTo. Both cases are being called with the exactly same task, session and location. The first call copies the location to a semi-permanent destination (and I confirmed that file is correct), and the second call fails on move because the destination already exists. I can obviously work around this fairly easily, but wondering if I'm missing something or if there's a bug. It does appear to happen more reliably when I background for 15 seconds or longer. A second issue which is reproducible is that while backgrounded, some files are completing downloads and never calling the download delegate's urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:) I tried resuming one or all of the tasks in applicationDidBecomeActive as suggested in multiple other forums posts, but neither of those seems to resolve the issue. Again, I can work around this (using a combination of totalBytesWritten and the known size of files which have completed downloads), but I'm wondering if I'm missing something obvious. I actually thought that perhaps the resume() workaround was causing the first issue, but removing it does not have an effect.
Replies
8
Boosts
0
Views
2.0k
Activity
1d
App Store Review Crash but no Crash Log
Hello, I've been trying the last week trying to get my app approved for the App Store. It's my first app and I'm not really sure what's going on. My app is getting rejected due to "App Completeness". Here's the rejection message: App Review Guideline Issue This is an automated message. The review of this submission cannot proceed. See below for more information. The app crashed after the initial launch. Apps that crash negatively impact users. Test the app on supported devices to identify and resolve crashes and stability issues before resubmitting for review. Learn more about testing a release build. When we submitted the first time we got rejected because our Apple sign in did not auto fill the user's name and we didn't have the EULA Link in the description. So the app didn't crash here as a tester sent screenshots and was in our app. We resubmitted and then we started getting these crashes. I examined the code we added from the first revision and tested the start up and everything worked fine on ours and our 30+ beta testers end. The thing is we're not getting a crash log from Apple testers or Apple's automated tester (if automated testing exists?). We are creating a fitness app that implements HealthKit. We have the required HealthShare and HealthUpdate messages in the signing and capabilities of our target. I'm not sure this would be the issue since the app actually executed the first run though. I've researched and some articles did say long load times on bad internet could make iOS terminate an app. So we worked to get our initial load network calls down from 10 seconds to about 1-2 seconds. This did not work either. We are using SwiftData to cache exercises fetched from our backend locally but we haven't made any changes to the entity's. So I wouldn't expect bad data to cause a crash especially because we flush even if it were bad data anyway. I've ran with instruments to see if this was a memory issue: With an Authed User with data loaded it gets to about 33MiB With a fresh install memory usage is about 17MiB I did have a point of interest in my profile: api.revenuecat.com is not listed in your app’s NSPrivacyTrackingDomain key in any privacy manifest. It may be following users across multiple apps and websites to create a profile about users of apps that contact this domain. I don't use revenue cat for tracking for Ads so I probably shouldn't add it to the NSPrivacyTrackingDomain right? I'm really lost here any advice would be much appreciated. I guess my questions are if Apple has an automating testing environment how can I closely match that for testing on my end? If this is an actual tester why am I not getting a crash log or steps to repeat this issue? Has anyone else experienced the pain I'm currently suffering?
Replies
0
Boosts
0
Views
179
Activity
1d
Custom keyboard extension left edge detecting touch after a second.
I'm creating a custom keyboard extension. So as a result, there are buttons which are pinned to the left edge of the keyboard. (Think of q key as an example). The logic of the key presses go something like this: Button detects a touchDown event and shows the magnified text which you normally see in system keyboard when tapping a key. Button detects a touchUpInside/touchDragOutside event and the magnified text disappears, again very similar to the system keyboard. This logic worked for all the buttons which were not pinned to the left edge of the keyboard. But for the buttons that were pinned to the left edge, the touchDown events were being detected after a second. So you can see this is obviously bad because I want to see the magnified text right after I place my finger on the button. WHAT I TRIED AS AN ALTERNATIVE: I removed all the touchDown, touchUpInside and touchDragOutside events from the button and disabled all their user interaction. Then I implemented to touches functions(touchesBegan, touchesEnded, etc.) and observed the touch locations on the background view. Surprisingly, even in this case, the touchesBegan function was called after a second after I placed my finger on the left edge of the screen and as usual, the touchesBegan function called just fine in the rest of the screen. Here's the code for the touches function: override func touchesBegan(_ touches: Set&lt;UITouch&gt;, with event: UIEvent?) { &#9;&#9;guard let touch = event?.allTouches?.first else { return } &#9;&#9;let location = touch.location(in: self.touchView) &#9;&#9;&#9;&#9; &#9;&#9;print(location) } What exactly is happening here? And what can I do to avoid this problem? NOTE: It works fine in simulator for some reason but has a problem with real devices.
Replies
1
Boosts
2
Views
554
Activity
2d
Issues with my APN tokens
Hey guys, I made a app that features push notificaions, and I keep having problems setting them up. It asks permissions, and then it says that it cannot get the APN token after 10 seconds, and I am positive that I have enabled Push Notificaions in the provisioning profile in Xcode. Can anyone help me fix this issue?
Replies
1
Boosts
0
Views
847
Activity
3d
deduplicated_symbol error
HI, I have a Swift UI app in the mac appstore in the upcoming release we have made lots of changes and it is working fine in debug mode but in production with testflight or direct distribution we are getting the following crash while working in the app. this is happening in the rendering phase. Thread 0 Crashed:: Dispatch queue: com.apple.main-thread 0 libswiftCore.dylib 0x19546f270 swift_unknownObjectRetain + 44 1 libswiftCore.dylib 0x1954bb09c swift_cvw_initWithCopyImpl(swift::OpaqueValue*, swift::OpaqueValue*, swift::TargetMetadata<swift::InProcess> const*) + 280 2 libswiftCore.dylib 0x1958f685c initializeWithCopy for ClosedRange<>.Index + 212 3 VirtualProg 0x104d73958 <deduplicated_symbol> + 56 How can i debug to find out what is causing the issue and fix it?. thanks in advance
Replies
2
Boosts
0
Views
98
Activity
4d
Live Activity / Dynamic Island countdown responds to manual device clock changes, while app timer and shielding remain correct
Our app runs offline-first focus sessions using FamilyControls / ManagedSettings shielding and DeviceActivity monitoring. The in-app session timer is protected against wall-clock manipulation by using monotonic elapsed time, and the shield remains active correctly when the user manually changes the iPhone clock. However, the Live Activity and Dynamic Island countdown appear to use the device's wall clock for their timer rendering. If the user changes the device time from Settings during an active session, the Live Activity / Dynamic Island countdown immediately jumps forward or backwards, even though the underlying session has not changed. Is there a recommended ActivityKit approach for rendering a Live Activity / Dynamic Island countdown that is resistant to manual device clock changes? If not, is this an expected limitation of Live Activity timer rendering? And is there any supported way for the host app or widget extension to detect wall-clock manipulation so the Live Activity can be corrected, dismissed, or replaced with a safer non-countdown state?
Replies
0
Boosts
0
Views
82
Activity
4d
String Catalogs auto-generated symbols located in Swift Packages with default Main Actor isolation don't compile with Xcode 26.4
Hello, I've already reported this issue via Feedback Assistant a month ago (FB22340897) but it's still open and I'd like to know whether I can expect something to be changed regarding it. Here are the details: It seems that Xcode 26.4 started specifying nonisolated for the resourceBundleDescription in the generated stringSymbols files for Swift packages: from: private let resourceBundleDescription = LocalizedStringResource.BundleDescription.atURL(resourceBundle.bundleURL) to: private nonisolated let resourceBundleDescription = LocalizedStringResource.BundleDescription.atURL(resourceBundle.bundleURL) This causes a compilation error: Main actor-isolated default value in a nonisolated context when the Package.swift for the Swift Package in which the string catalog is located specifies: swiftSettings: [.defaultIsolation(MainActor.self)] Since all tools (String Catalogs, Swift Packages and default actor isolation to be Main Actor) are recommended by Apple, I believe it should be possible to use all these together like before Xcode 26.4.
Replies
1
Boosts
0
Views
698
Activity
5d
Bundle preferred languages mechanism
Hi there, I’m curious to understand how the system determines which language to use for an app. The system is currently set to en-IN (English - India). My app supports the following languages: en (the default development language) en-GB (United Kingdom) en-IE (Ireland) en-US (United States) When I run the app, the Bundle.main.preferredLanguages returns [„en-GB“, „en“], which causes the app to be set to en-GB. However, when the app doesn’t support the preferred system language, I would expect it to default to the en language. Surprisingly, this is not the case. This behavior is precisely described in Technical Note TN2418. Unfortunately, there’s no explanation provided. Is this behavior related to the CLDR Linguistic Distance? I also attempted to replace the default development language en with en-001 (English - world), but it had no effect.
Replies
3
Boosts
0
Views
149
Activity
1w
How to detect if a binding is from a state or a constant?
Hi, I'm trying to create a custom TextField component where we can have our own custom FormatStyle as a param and then it will change the value binding according to the FormatStyle. It worked with State<Any?> like for example $textValue. But when I use .constant(2000) for instance, the Formatting doesn't work. So is there any way to detect whether the value param is constant or not? Thank you.
Replies
0
Boosts
0
Views
80
Activity
1w
macOS main.swift and Main actor-isolated conformance cannot be used in nonisolated context
For a simple, resourceless cocoa apps I used to manually setup the application lifecycle (mimicking what's documented here: https://developer.apple.com/documentation/appkit/nsapplication), so my main.swift would look like: import Cocoa let delegate = SomeDelegate() _ = NSApplication.shared NSApp.delegate = delegate NSApp.run() This triggers a warning in Xcode 26.2: "Main actor-isolated conformance of SomeDelegate cannot be used in nonisolated context; this is an error in Swift 6 language mode". so what is the recommended way to refactor above so that it is Swift 6 compliant?
Replies
1
Boosts
0
Views
709
Activity
1w
Storefront.current?.countryCode returns inconsistent values in TestFlight builds
Hi, We're experiencing inconsistent and unexpected values returned by Storefront.current?.countryCode when running our app via TestFlight. In our case: The device region and locale are set to Poland The App Store account (Media & Purchases) is also set to Poland However, when running a TestFlight build, Storefront.current?.countryCode sometimes returns a completely different value (e.g. "NO" for Norway), which does not match the current App Store account configuration. Here's the code we're using: if #available(iOS 15.0, *) { let code = await Storefront.current?.countryCode print("Storefront countryCode:", code ?? "nil") } What's particularly confusing: Across different devices logged into the same App Store account, we sometimes receive different countryCode values The returned value does not seem to reflect the current App Store region or device settings We understand that Storefront reflects the App Store storefront and not the device locale, but in this case the value appears stale or incorrect even with a properly configured App Store account. Questions: Is Storefront.current?.countryCode expected to behave differently in TestFlight vs. production builds? Are there known caching or propagation delays for storefront updates across devices? Can TestFlight builds return outdated or inconsistent storefront values? What is the recommended way to reliably determine the user's App Store region in this scenario? We rely on storefront to determine regional availability of features, so understanding this behavior is important for us. Thanks in advance for any clarification!
Replies
1
Boosts
0
Views
94
Activity
1w
Understanding '.waiting' state in NWConnection.State for UDP
While going through the documentation for NWConnection, there seems to be state known as .waiting which means that the connection is waiting for a path change. For TCP, the state is understandable and can occur under some scenarios. But for the case of UDP, I have following queries: Why do we need .waiting state for the case of UDP? Even if we do need .waiting state for UDP, when all does this state occurs?
Replies
3
Boosts
0
Views
172
Activity
1w
AppStore.sync() not restoring purchases
On an app that was using the old API for In-App Purchases (StoreKit 1). The app is already published on the App Store. The purchase is non-consumable. While trying to migrate to StoreKit 2, I'm unable to restore purchases. Specifically displaying and purchasing products works as expected, but when deleting and reinstalling the app, and then trying to restore purchases I can't do it. I'm trying to restore them using the new APIs but it doesn't seem to be working. What I have tried so far: I'm listening for transaction updates during the whole lifetime of the app, with: Task.detached { for await result in Transaction.updates { if case let .verified(safe) = result { } } } I have a button that calls this method, but other than prompting to log in again with the Apple ID it doesn't seem to have any effect at all: try? await AppStore.sync() This doesn't return any item for await result in Transaction.currentEntitlements { if case let .verified(transaction) = result { } } This doesn't return any item for await result in Transaction.all { if case let .verified(transaction) = result { } } As mentioned before I'm trying this after purchasing the item and deleting the app. So I'm sure it should be able to restore the purchase. Am trying this both with a Configuration.storekit file on the simulator, and without it on a real device, in the Sandbox Environment. Has anyone being able to restore purchases using StoreKit 2? PD: I already filed a feedback report on Feedback Assistant, but so far the only thing that they have replied is: Because StoreKit Testing in Xcode is a local environment, and the data is tied to the app, when you delete the app you're also deleting all the transaction data for that app in the Xcode environment. The code snippets provided are correct usage of the API. So yes, using a Configuration.storekit file won't work on restoring purchases, but if I can't restore them on the Sandbox Environment I'm afraid that this won't work once released, leaving my users totally unable to restore what they have already purchased.
Replies
3
Boosts
0
Views
1.9k
Activity
1w
SwiftUI View Not Initialized on Background Relaunch (CoreBluetooth / Cold Start?)
I have a question regarding cold start and pre-warming behavior on iOS. I’m developing a SwiftUI app that continuously receives data from a BLE device in the background. We’ve observed that after the BLE stream stops, the OS often terminates our app. Later, when the sensor comes back into range, iOS appears to relaunch (or reinitialize) the app. In our app, we use a WindowGroup like this: WindowGroup { AppView(store: store) } We’ve placed our BLE reconnection logic inside a .task modifier in AppView. What’s confusing is this: Most of the time, when the app is relaunched, AppView is created and the .task runs as expected. However, in about 1 out of 10 cases, AppView is not created at all, so the .task does not execute. I’m trying to understand: Under what conditions does iOS relaunch an app without fully initializing the SwiftUI view hierarchy? Is this related to pre-warming or background relaunch mechanisms (e.g., CoreBluetooth state restoration)? What determines whether the WindowGroup and root view are actually instantiated? Any insight into the system’s relaunch behavior or lifecycle in this scenario would be greatly appreciated.
Replies
2
Boosts
0
Views
146
Activity
1w
The size of the asset has increased more than three time in the assets.car file after signing the ios app
The assets in the Asset.xcasset lesser than the asset in the Assets.car file. Because of this the iPA file size increased three times as Assets.car file inside the iPA increased. Why do the asset file size increased enormously. How do we prevent this ? I used Version 26.2 (17C52).
Replies
1
Boosts
1
Views
313
Activity
1w
SCNTechnique clearColor Always Shows sceneBackground When Passes Share Depth Buffer
Problem Description I'm encountering an issue with SCNTechnique where the clearColor setting is being ignored when multiple passes share the same depth buffer. The clear color always appears as the scene background, regardless of what value I set. The minimal project for reproducing the issue: https://www.dropbox.com/scl/fi/30mx06xunh75wgl3t4sbd/SCNTechniqueCustomSymbols.zip?rlkey=yuehjtk7xh2pmdbetv2r8t2lx&st=b9uobpkp&dl=0 Problem Details In my SCNTechnique configuration, I have two passes that need to share the same depth buffer for proper occlusion handling: "passes": [ "box1_pass": [ "draw": "DRAW_SCENE", "includeCategoryMask": 1, "colorStates": [ "clear": true, "clearColor": "0 0 0 0" // Expecting transparent black ], "depthStates": [ "clear": true, "enableWrite": true ], "outputs": [ "depth": "box1_depth", "color": "box1_color" ], ], "box2_pass": [ "draw": "DRAW_SCENE", "includeCategoryMask": 2, "colorStates": [ "clear": true, "clearColor": "0 0 0 0" // Also expecting transparent black ], "depthStates": [ "clear": false, "enableWrite": false ], "outputs": [ "depth": "box1_depth", // Sharing the same depth buffer "color": "box2_color", ], ], "final_quad": [ "draw": "DRAW_QUAD", "metalVertexShader": "myVertexShader", "metalFragmentShader": "myFragmentShader", "inputs": [ "box1_color": "box1_color", "box2_color": "box2_color", ], "outputs": [ "color": "COLOR" ] ] ] And the metal shader used to display box1_color and box2_color with splitting: fragment half4 myFragmentShader(VertexOut in [[stage_in]], texture2d<half, access::sample> box1_color [[texture(0)]], texture2d<half, access::sample> box2_color [[texture(1)]]) { half4 color1 = box1_color.sample(s, in.texcoord); half4 color2 = box2_color.sample(s, in.texcoord); if (in.texcoord.x < 0.5) { return color1; } return color2; }; Expected Behavior Both passes should clear their color targets to transparent black (0, 0, 0, 0) The depth buffer should be shared between passes for proper occlusion Actual Behavior Both box1_color and box2_color targets contain the scene background instead of being cleared to transparent (see attached image) This happens even when I explicitly set clearColor: "0 0 0 0" for both passes Setting scene.background.contents = UIColor.clear makes the clearColor work as expected, but I need to keep the scene background for other purposes What I've Tried Setting different clearColor values - all are ignored when sharing depth buffer Using DRAW_NODE instead of DRAW_SCENE - didn't solve the issue Creating a separate pass to capture the background - the background still appears in the other passes Various combinations of clear flags and render orders Environment iOS/macOS, running with "My Mac (Designed for iPad)" Xcode 16.2 Question Is this a known limitation of SceneKit when passes share a depth buffer? Is there a workaround to achieve truly transparent clear colors while maintaining a shared depth buffer for occlusion testing? The core issue seems to be that SceneKit automatically renders the scene background in every DRAW_SCENE pass when a shared depth buffer is detected, overriding any clearColor settings. Any insights or workarounds would be greatly appreciated. Thank you!
Replies
1
Boosts
0
Views
719
Activity
2w
NEURLFilter Not Blocking urls
Hi I tried to follow this guide https://developer.apple.com/documentation/networkextension/filtering-traffic-by-url I downloaded the sample app and put our pir service server address in the app. The service is already running and the app is connected to the pir service but the url is still not blocked. We tried to block example.com. Is there anything that we need to do in iOS code? This is the sample when there's dataset This is the sample when there's no dataset
Replies
1
Boosts
0
Views
98
Activity
2w
iOS crash: EXC_BAD_ACCESS in iOS 26+ when mouting/dismounting WebView
I'm experiencing a native crash on iOS 26+ with WebKit with title: EXC_BAD_ACCESS (KERN_INVALID_ADDRESS). The stack trace points to UIKit/WebKit animation and context menu handling, and the crash occurs while a WebView is presented or dismissed. Crashed: com.apple.main-thread 0 WebKit 0x7bcfac <redacted> + 12 1 WebKit 0xaf5c34 <redacted> + 84 2 UIKitCore 0x34ebdc -[_UIContextMenuAnimator performAllCompletions] + 248 3 UIKitCore 0x7f997c block_destroy_helper.72 + 1840 4 UIKitCore 0x7fb4b4 objectdestroy.36Tm + 88 5 UIKitCore 0x7ad354 objectdestroy.3Tm + 30500 6 UIKitCore 0x5c0e5c __swift_memcpy192_8 + 4352 7 UIKitCore 0x21944 block_copy_helper.374 + 40 8 UIKitCore 0x1dc174 -[_UIGroupCompletion _performAllCompletions] + 160 9 UIKitCore 0x35d0c4 -[_UIGravityWellEffectBody .cxx_destruct] + 180 10 UIKitCore 0x215018 -[UIScrollView _contentLayoutGuideIfExists] + 72 11 UIKitCore 0x943e4 NSStringFromUIEdgeInsets + 304 12 UIKitCore 0x94348 NSStringFromUIEdgeInsets + 148 13 UIKitCore 0x8f598 __UIVIEW_IS_EXECUTING_ANIMATION_COMPLETION_BLOCK__ + 36 14 UIKitCore 0x1995d8c -[UIViewAnimationBlockDelegate _sendDeferredCompletion:] + 92 15 libdispatch.dylib 0x1adc _dispatch_call_block_and_release + 32 16 libdispatch.dylib 0x1b7fc _dispatch_client_callout + 16 17 libdispatch.dylib 0x38b10 _dispatch_main_queue_drain.cold.5 + 812 18 libdispatch.dylib 0x10ec8 _dispatch_main_queue_drain + 180 19 libdispatch.dylib 0x10e04 _dispatch_main_queue_callback_4CF + 44 20 CoreFoundation 0x6a2b4 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 16 21 CoreFoundation 0x1db3c __CFRunLoopRun + 1944 22 CoreFoundation 0x1ca6c _CFRunLoopRunSpecificWithOptions + 532 23 GraphicsServices 0x1498 GSEventRunModal + 120 24 UIKitCore 0x9ddf8 -[UIApplication _run] + 792 25 UIKitCore 0x46e54 UIApplicationMain + 336 26 - 0xedf88 main + 24 (AppDelegate.swift:24) 27 ??? 0x196686e28 (Missing)
Replies
0
Boosts
0
Views
102
Activity
2w