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

Posts under Swift tag

200 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
2.0k
Oct ’25
Programatically adding to a TextField and moving the TextSelection point in SwiftUI
Hi! I am trying to create a simple SwiftUI TextField, with an external button to add text to the field at the current insertion point (the cursor in the TextField). When I add the text, the cursor (I-Beam) remains at the original insertion point, so I want it to move over to the end of what I added. The trouble is, it sometimes moves further forward or to the end (visibly) but works as if it is still at the point I moved it to. This seems to possibly be due to emojis in the TextField (because, I assume, they are composed of more bytes). Further, sometimes the addition of the text can cause an emoji to appear unexpectedly, I assume because it is combining the bytes in an odd way. So moving the cursor seems to sometimes introduce weird behaviour. This comes from a much larger project, but I have distilled this down to the smallest example project I could. And I have a video to show how it behaves. Here's the main part of the code, and I'll attach an Xcode project: import SwiftUI struct ContentView: View { @State private var text: String = "abcdef🧁🧁🧁🧁ghijkl" @State private var selectedText: TextSelection? var body: some View { VStack { TextField("", text: $text, selection: $selectedText) .font(.title) Button("Add Z at Insertion Point in TextField") { // Get indices of any selection in the text field let from: String.Index, to: String.Index if let selectedText = selectedText { let indices = selectedText.indices switch indices { case .selection(let range): from = range.lowerBound to = range.upperBound case .multiSelection(let rangeSet): from = rangeSet.ranges.first!.lowerBound to = rangeSet.ranges.first!.upperBound default: from = self.text.endIndex to = self.text.endIndex } } else { from = self.text.endIndex to = self.text.endIndex } guard from <= to && from <= self.text.endIndex else { return } // Insert and update the cursor position self.text.replaceSubrange(from..<to, with: "Z") // Move cursor after the inserted character let newIndex = self.text.index(after: from) selectedText = TextSelection(insertionPoint: newIndex) } } .padding() } } STEPS TO REPRODUCE Run the app. Also view the video as it shows the steps. Put insertion point between c and d. Press the "Add Z" button. Note that Z is placed between c and d. This is great. Put insertion point between h and i. Press the "Add Z" button. Note that Z is placed between h and i. BUT, the insertion point I-beam moves to the end of the string. Press the "Add Z" button again. Z is added where you would have expected based on where the TextSelection insertion point was put, but the flashing I-Beam is still at the end. Press the "Add Z" button again. Same issue. insertion point is being shown at end, but to the button it is between Z and i. OF NOTE, if you use the keyboard and press delete, it deletes from end (where the I-beam is). Now put insertion point between the 4 cupcakes. Press "Add Z" two times. It behaves correctly. Press "Add Z" a third time. It adds a fairy emoji. So, any idea what I am doing wrong? I thought it might be an issue requiring me to update in a background thread, but I tried that, even delaying the update in the thread, but the issue remains. Thanks in advance. Here's a video: https://curmi.name/temp/SimpleTextField%20showing%20issues.mp4 And if it helps, here is the Xcode project: https://curmi.name/temp/SimpleTextfield.zip
0
0
98
17h
Sending 'geoRegion' risks causing data races
I have this simple piece of code that of course correctly ran in Swift 5: func geoRegion()-> CLRegion?{ guard let location=referenceLocation else{ return nil } return CLCircularRegion(center:location.coordinate, radius:50000, identifier:"georeferencing") } func placemarksForAddress(_ address: String) async throws -> [CLPlacemark]?{ if let placemark=placemarkCache[address]{ if placemark.location!.distance(from: referenceLocation!)<100000{ return [placemark] } } do{ guard let geoRegion=self.geoRegion() else { return nil } let placemarks = try await georeferenceQueue.geocodeAddressString( address, in: geoRegion) if placemarks.count>=0{ self.placemarkCache[address]=MKPlacemark(placemark: placemarks[0]) return placemarks } } catch { let placemarks=try await self.placemarkForLocation(referenceLocation) return placemarks } return nil } That now presents error: Sending task-isolated 'geoRegion' to actor-isolated instance method 'geocodeAddressString(_:in:)' risks causing data races between actor-isolated and task-isolated uses
4
0
412
1d
AuditToken and SecCodeCopySigningInformation
In our macOS solution, we have a few processes and a few plugin modules which communicate with each other over XPC. We have recently started enforcing library validation flag along with hardened runtime for all processes and plugins. To enforce that, we are trying to get signing information from the XPC audit token using SecCodeCopySigningInformation with kSecCSDynamicInformation flag. As per documentation, this flag requires a live SecCode not SecStaticCode to be passed to SecCodeCopySigningInformation. However, SecCodeCopySigningInformation explicitly requires SecStaticCode in its parameters. So I am unsure how to pass live SecCode to SecCodeCopySigningInformation without copying SecStaticCode from it using SecCodeCopyStaticCode. Force cast from SecCode to SecStaticCode fails. Is unsafeBitCast a valid option in this case? Note that we support macOS version 12 and later.
1
0
46
1d
A Repeating timer in Swift 6
I'm using that repeating timer for processing information repeatedly: actor RepeatingTimer { private var task: Task<Void, Never>? private var isPaused = false func start(duration: Double, onTick: @escaping () -> Void) { task?.cancel() // Cancel any existing timer isPaused = false task = Task { while !Task.isCancelled { // Check if paused if !isPaused { onTick() } // Sleep for the interval try? await Task.sleep(for: .seconds(duration)) } } } func pause() { isPaused = true } func resume() { isPaused = false } func stop() { task?.cancel() task = nil } }` Yet when I call it from another actor with: await timer.start(duration: interval, onTick:{ self.process() }) I get: Sending 'self'-isolated value of non-Sendable type '() -> ()' to actor-isolated instance method 'start(duration:onTick:)' risks causing races in between 'self'-isolated and actor-isolated uses Is there some more stable option for managing repeating timers, or how to solve this error?
4
0
540
2d
MKMapView realistic elevationStyle cannot combine with overlays
I have an MKMapView displaying realistic elevation. As soon as I call "mapView.addOverlays([polylines])" which then trigger: func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer { if let polyline = overlay as? MKPolyline { let view = MKPolylineRenderer(polyline: polyline) // ... return view } return MKOverlayRenderer(overlay: overlay) } The map instantly turn flat until I remove all the overlays.
3
0
61
2d
iOS 26.0+: Liquid Glass views don't respect named colors
Hello, I'm a bit new to iOS development, so this could be something I've overlooked, but I've tried a bunch of things on my own and with the help of Copilot, as well as some senior engineers here at my company. I let AI summarize what the problem is, what I've tried, what doesn't work, and also some information on the system: Problem: UITabBarAppearance Custom Colors Ignored - All Diagnostics Show Correct Configuration Environment: iOS Deployment Target: 13.4 Xcode: Latest (26.4.1 as of writing) Device/Simulator: Both affected Language: Swift UI: UIKit with Storyboards Description: Tab bar selected item displays system default colors (gray in light mode, white in dark mode) instead of my custom named color from asset catalog. System colors like .systemBlue work correctly, but custom asset catalog colors are completely ignored. Expected behavior: Selected tab bar item should display BlueTVColor2 (RGB 0, 0.173, 0.38 in light mode; RGB 0, 0.569, 1.0 in dark mode) Actual behaviour: Selected tab bar item displays gray/white/black system defaults What I've Verified Works Correctly: Color resolution: let color = UIColor(named: "BlueTVColor2") print(color) // Resolves correctly print(color?.resolvedColor(with: .init(userInterfaceStyle: .light))) // RGB(0, 0.173, 0.38) print(color?.resolvedColor(with: .init(userInterfaceStyle: .dark))) // RGB(0, 0.569, 1.0) Asset Catalog Configuration: BlueTVColor2.colorset has both light and dark variants template-rendering-intent: template set on all tab bar images All images use .alwaysTemplate rendering mode (verified at runtime) UITabBarAppearance Configuration (Although I've also tried just directly in the storyboard, it didn't work, the below is in code-behind): override func viewDidLoad() { super.viewDidLoad() let selectedColor = UIColor(named: "BlueTVColor2")!.resolvedColor(with: traitCollection) let normalColor = UIColor.redTVColor.resolvedColor(with: traitCollection) let appearance = UITabBarAppearance() appearance.configureWithOpaqueBackground() let itemAppearance = UITabBarItemAppearance() itemAppearance.selected.iconColor = selectedColor itemAppearance.selected.titleTextAttributes = [.foregroundColor: selectedColor] itemAppearance.normal.iconColor = normalColor appearance.stackedLayoutAppearance = itemAppearance appearance.inlineLayoutAppearance = itemAppearance appearance.compactInlineLayoutAppearance = itemAppearance tabBar.isTranslucent = false tabBar.standardAppearance = appearance if #available(iOS 15.0, *) { tabBar.scrollEdgeAppearance = appearance } tabBar.tintColor = selectedColor tabBar.unselectedItemTintColor = normalColor } Runtime Diagnostics Confirm Everything is Set Correctly: Appearance selected iconColor: RGB(0, 0.569, 1) // Correct Tab bar standardAppearance selected iconColor: RGB(0, 0.569, 1) // Correct Tab bar tintColor: RGB(0, 0.569, 1) // Correct Tab bar unselectedItemTintColor: RGB(1, 0.259, 0.271) // Correct All tab bar item images: Rendering mode = 2 (.alwaysTemplate) // Correct Settings persist through viewDidAppear // Correct Yet the UI displays system default gray/white/black colors. What I've Tried (All Failed): Deprecated selectedImageTintColor property (returns nil when standardAppearance is set) Both configureWithDefaultBackground() and configureWithOpaqueBackground() Dynamic colors vs resolved fixed colors Configuring all layout appearances (stacked, inline, compactInline) Setting isTranslucent = false Re-applying appearance in viewDidAppear with delayed dispatch Manually re-applying template rendering mode to images at runtime Removing storyboard color configuration entirely Changing global accent color build setting System colors (.systemBlue) work fine; only custom asset catalog colors fail Additional Context: This is a legacy project originally created around 2013-2015, migrated to modern Swift/iOS (not everywhere, major parts are still using objc, UIKit/Storyboard) When I set tabBar.tintColor = .systemBlue it works perfectly The color BlueTVColor2 is used successfully elsewhere in the app (also if setting it as the background of the UITabBar, it works, just not as a tint for the icons/text) Storyboard has no selectedImageTintColor set (removed during debugging) No UITabBar.appearance() proxy calls anywhere in codebase Deployment target is iOS 13.4 (when UITabBarAppearance was introduced) Pre iOS 26.0, the adding of the tint color to the UITabBar worked as intended, so this has come as a result of the update to iOS 26.0 in some way Comparison with Working Test Project: Created a fresh iOS project with same setup - custom asset catalog colors work perfectly in tab bar with identical UITabBarAppearance configuration. Question: Why would UITabBarAppearance properties show correct colors in diagnostics but render with system defaults? Is there a known issue with asset catalog named colors in UITabBarAppearance on iOS 13.4+? Could legacy project settings interfere with modern appearance API? Any insights would be greatly appreciated. I'm running out of ideas and this seems like either a framework bug or some undocumented interaction between asset catalogs and tab bar appearance. Code Sample: I can't release much code besides just things I've worked on, so hopefully this full description of the problem and everything I've tried can help illuminate the issue at hand. I've tried all of the above and probably more the past week and can't make heads or tails of where the issue is located. The best I can come up with right now is some sort of compatibility issues but I have no way of determining where it is that I should investigate and fix.
1
0
52
2d
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?
1
1
224
5d
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
384
1w
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
2k
1w
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.
1
2
605
1w
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
1.5k
1w
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
139
1w
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
119
1w
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
952
1w
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
226
2w
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
122
2w
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
787
2w
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
118
2w
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
190
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
2.0k
Activity
Oct ’25
Programatically adding to a TextField and moving the TextSelection point in SwiftUI
Hi! I am trying to create a simple SwiftUI TextField, with an external button to add text to the field at the current insertion point (the cursor in the TextField). When I add the text, the cursor (I-Beam) remains at the original insertion point, so I want it to move over to the end of what I added. The trouble is, it sometimes moves further forward or to the end (visibly) but works as if it is still at the point I moved it to. This seems to possibly be due to emojis in the TextField (because, I assume, they are composed of more bytes). Further, sometimes the addition of the text can cause an emoji to appear unexpectedly, I assume because it is combining the bytes in an odd way. So moving the cursor seems to sometimes introduce weird behaviour. This comes from a much larger project, but I have distilled this down to the smallest example project I could. And I have a video to show how it behaves. Here's the main part of the code, and I'll attach an Xcode project: import SwiftUI struct ContentView: View { @State private var text: String = "abcdef🧁🧁🧁🧁ghijkl" @State private var selectedText: TextSelection? var body: some View { VStack { TextField("", text: $text, selection: $selectedText) .font(.title) Button("Add Z at Insertion Point in TextField") { // Get indices of any selection in the text field let from: String.Index, to: String.Index if let selectedText = selectedText { let indices = selectedText.indices switch indices { case .selection(let range): from = range.lowerBound to = range.upperBound case .multiSelection(let rangeSet): from = rangeSet.ranges.first!.lowerBound to = rangeSet.ranges.first!.upperBound default: from = self.text.endIndex to = self.text.endIndex } } else { from = self.text.endIndex to = self.text.endIndex } guard from <= to && from <= self.text.endIndex else { return } // Insert and update the cursor position self.text.replaceSubrange(from..<to, with: "Z") // Move cursor after the inserted character let newIndex = self.text.index(after: from) selectedText = TextSelection(insertionPoint: newIndex) } } .padding() } } STEPS TO REPRODUCE Run the app. Also view the video as it shows the steps. Put insertion point between c and d. Press the "Add Z" button. Note that Z is placed between c and d. This is great. Put insertion point between h and i. Press the "Add Z" button. Note that Z is placed between h and i. BUT, the insertion point I-beam moves to the end of the string. Press the "Add Z" button again. Z is added where you would have expected based on where the TextSelection insertion point was put, but the flashing I-Beam is still at the end. Press the "Add Z" button again. Same issue. insertion point is being shown at end, but to the button it is between Z and i. OF NOTE, if you use the keyboard and press delete, it deletes from end (where the I-beam is). Now put insertion point between the 4 cupcakes. Press "Add Z" two times. It behaves correctly. Press "Add Z" a third time. It adds a fairy emoji. So, any idea what I am doing wrong? I thought it might be an issue requiring me to update in a background thread, but I tried that, even delaying the update in the thread, but the issue remains. Thanks in advance. Here's a video: https://curmi.name/temp/SimpleTextField%20showing%20issues.mp4 And if it helps, here is the Xcode project: https://curmi.name/temp/SimpleTextfield.zip
Replies
0
Boosts
0
Views
98
Activity
17h
Type 'class' does not conform to protocol 'protocol'
I inherit from a protocol that implements in its extension those functions, that should not be required by the adopting class and instead I get those errors. Could someone explain why those errors appear and how to fix it.
Replies
5
Boosts
0
Views
132
Activity
1d
Sending 'geoRegion' risks causing data races
I have this simple piece of code that of course correctly ran in Swift 5: func geoRegion()-> CLRegion?{ guard let location=referenceLocation else{ return nil } return CLCircularRegion(center:location.coordinate, radius:50000, identifier:"georeferencing") } func placemarksForAddress(_ address: String) async throws -> [CLPlacemark]?{ if let placemark=placemarkCache[address]{ if placemark.location!.distance(from: referenceLocation!)<100000{ return [placemark] } } do{ guard let geoRegion=self.geoRegion() else { return nil } let placemarks = try await georeferenceQueue.geocodeAddressString( address, in: geoRegion) if placemarks.count>=0{ self.placemarkCache[address]=MKPlacemark(placemark: placemarks[0]) return placemarks } } catch { let placemarks=try await self.placemarkForLocation(referenceLocation) return placemarks } return nil } That now presents error: Sending task-isolated 'geoRegion' to actor-isolated instance method 'geocodeAddressString(_:in:)' risks causing data races between actor-isolated and task-isolated uses
Replies
4
Boosts
0
Views
412
Activity
1d
AuditToken and SecCodeCopySigningInformation
In our macOS solution, we have a few processes and a few plugin modules which communicate with each other over XPC. We have recently started enforcing library validation flag along with hardened runtime for all processes and plugins. To enforce that, we are trying to get signing information from the XPC audit token using SecCodeCopySigningInformation with kSecCSDynamicInformation flag. As per documentation, this flag requires a live SecCode not SecStaticCode to be passed to SecCodeCopySigningInformation. However, SecCodeCopySigningInformation explicitly requires SecStaticCode in its parameters. So I am unsure how to pass live SecCode to SecCodeCopySigningInformation without copying SecStaticCode from it using SecCodeCopyStaticCode. Force cast from SecCode to SecStaticCode fails. Is unsafeBitCast a valid option in this case? Note that we support macOS version 12 and later.
Replies
1
Boosts
0
Views
46
Activity
1d
A Repeating timer in Swift 6
I'm using that repeating timer for processing information repeatedly: actor RepeatingTimer { private var task: Task<Void, Never>? private var isPaused = false func start(duration: Double, onTick: @escaping () -> Void) { task?.cancel() // Cancel any existing timer isPaused = false task = Task { while !Task.isCancelled { // Check if paused if !isPaused { onTick() } // Sleep for the interval try? await Task.sleep(for: .seconds(duration)) } } } func pause() { isPaused = true } func resume() { isPaused = false } func stop() { task?.cancel() task = nil } }` Yet when I call it from another actor with: await timer.start(duration: interval, onTick:{ self.process() }) I get: Sending 'self'-isolated value of non-Sendable type '() -> ()' to actor-isolated instance method 'start(duration:onTick:)' risks causing races in between 'self'-isolated and actor-isolated uses Is there some more stable option for managing repeating timers, or how to solve this error?
Replies
4
Boosts
0
Views
540
Activity
2d
MKMapView realistic elevationStyle cannot combine with overlays
I have an MKMapView displaying realistic elevation. As soon as I call "mapView.addOverlays([polylines])" which then trigger: func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer { if let polyline = overlay as? MKPolyline { let view = MKPolylineRenderer(polyline: polyline) // ... return view } return MKOverlayRenderer(overlay: overlay) } The map instantly turn flat until I remove all the overlays.
Replies
3
Boosts
0
Views
61
Activity
2d
iOS 26.0+: Liquid Glass views don't respect named colors
Hello, I'm a bit new to iOS development, so this could be something I've overlooked, but I've tried a bunch of things on my own and with the help of Copilot, as well as some senior engineers here at my company. I let AI summarize what the problem is, what I've tried, what doesn't work, and also some information on the system: Problem: UITabBarAppearance Custom Colors Ignored - All Diagnostics Show Correct Configuration Environment: iOS Deployment Target: 13.4 Xcode: Latest (26.4.1 as of writing) Device/Simulator: Both affected Language: Swift UI: UIKit with Storyboards Description: Tab bar selected item displays system default colors (gray in light mode, white in dark mode) instead of my custom named color from asset catalog. System colors like .systemBlue work correctly, but custom asset catalog colors are completely ignored. Expected behavior: Selected tab bar item should display BlueTVColor2 (RGB 0, 0.173, 0.38 in light mode; RGB 0, 0.569, 1.0 in dark mode) Actual behaviour: Selected tab bar item displays gray/white/black system defaults What I've Verified Works Correctly: Color resolution: let color = UIColor(named: "BlueTVColor2") print(color) // Resolves correctly print(color?.resolvedColor(with: .init(userInterfaceStyle: .light))) // RGB(0, 0.173, 0.38) print(color?.resolvedColor(with: .init(userInterfaceStyle: .dark))) // RGB(0, 0.569, 1.0) Asset Catalog Configuration: BlueTVColor2.colorset has both light and dark variants template-rendering-intent: template set on all tab bar images All images use .alwaysTemplate rendering mode (verified at runtime) UITabBarAppearance Configuration (Although I've also tried just directly in the storyboard, it didn't work, the below is in code-behind): override func viewDidLoad() { super.viewDidLoad() let selectedColor = UIColor(named: "BlueTVColor2")!.resolvedColor(with: traitCollection) let normalColor = UIColor.redTVColor.resolvedColor(with: traitCollection) let appearance = UITabBarAppearance() appearance.configureWithOpaqueBackground() let itemAppearance = UITabBarItemAppearance() itemAppearance.selected.iconColor = selectedColor itemAppearance.selected.titleTextAttributes = [.foregroundColor: selectedColor] itemAppearance.normal.iconColor = normalColor appearance.stackedLayoutAppearance = itemAppearance appearance.inlineLayoutAppearance = itemAppearance appearance.compactInlineLayoutAppearance = itemAppearance tabBar.isTranslucent = false tabBar.standardAppearance = appearance if #available(iOS 15.0, *) { tabBar.scrollEdgeAppearance = appearance } tabBar.tintColor = selectedColor tabBar.unselectedItemTintColor = normalColor } Runtime Diagnostics Confirm Everything is Set Correctly: Appearance selected iconColor: RGB(0, 0.569, 1) // Correct Tab bar standardAppearance selected iconColor: RGB(0, 0.569, 1) // Correct Tab bar tintColor: RGB(0, 0.569, 1) // Correct Tab bar unselectedItemTintColor: RGB(1, 0.259, 0.271) // Correct All tab bar item images: Rendering mode = 2 (.alwaysTemplate) // Correct Settings persist through viewDidAppear // Correct Yet the UI displays system default gray/white/black colors. What I've Tried (All Failed): Deprecated selectedImageTintColor property (returns nil when standardAppearance is set) Both configureWithDefaultBackground() and configureWithOpaqueBackground() Dynamic colors vs resolved fixed colors Configuring all layout appearances (stacked, inline, compactInline) Setting isTranslucent = false Re-applying appearance in viewDidAppear with delayed dispatch Manually re-applying template rendering mode to images at runtime Removing storyboard color configuration entirely Changing global accent color build setting System colors (.systemBlue) work fine; only custom asset catalog colors fail Additional Context: This is a legacy project originally created around 2013-2015, migrated to modern Swift/iOS (not everywhere, major parts are still using objc, UIKit/Storyboard) When I set tabBar.tintColor = .systemBlue it works perfectly The color BlueTVColor2 is used successfully elsewhere in the app (also if setting it as the background of the UITabBar, it works, just not as a tint for the icons/text) Storyboard has no selectedImageTintColor set (removed during debugging) No UITabBar.appearance() proxy calls anywhere in codebase Deployment target is iOS 13.4 (when UITabBarAppearance was introduced) Pre iOS 26.0, the adding of the tint color to the UITabBar worked as intended, so this has come as a result of the update to iOS 26.0 in some way Comparison with Working Test Project: Created a fresh iOS project with same setup - custom asset catalog colors work perfectly in tab bar with identical UITabBarAppearance configuration. Question: Why would UITabBarAppearance properties show correct colors in diagnostics but render with system defaults? Is there a known issue with asset catalog named colors in UITabBarAppearance on iOS 13.4+? Could legacy project settings interfere with modern appearance API? Any insights would be greatly appreciated. I'm running out of ideas and this seems like either a framework bug or some undocumented interaction between asset catalogs and tab bar appearance. Code Sample: I can't release much code besides just things I've worked on, so hopefully this full description of the problem and everything I've tried can help illuminate the issue at hand. I've tried all of the above and probably more the past week and can't make heads or tails of where the issue is located. The best I can come up with right now is some sort of compatibility issues but I have no way of determining where it is that I should investigate and fix.
Replies
1
Boosts
0
Views
52
Activity
2d
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
1
Boosts
1
Views
224
Activity
5d
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
384
Activity
1w
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
2k
Activity
1w
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
605
Activity
1w
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
1.5k
Activity
1w
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
139
Activity
1w
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
119
Activity
1w
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
952
Activity
1w
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
226
Activity
2w
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
122
Activity
2w
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
787
Activity
2w
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
118
Activity
2w
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
190
Activity
2w