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
2k
Oct ’25
Issues with TCP Socket Management and Ghost Data on ESP32 (Swift)
Hi everyone, I'm developing an iOS app using Swift (Foundation, Network, and Combine) that communicates via TCP with a weighing scale. The scale uses an internal ESP32 module acting as a Wi-Fi Access Point (no internet access) specifically for data transmission. The app connects to this network and opens a socket to receive weight data and send command strings. I’m currently facing two main issues: Socket Management: The socket isn't closing properly. Occasionally, the app opens multiple simultaneous connections instead of maintaining a single one. Since the ESP32 has a client limit, these ghost connections eventually hang the communication module. Invalid Outbound Data: The connection drops frequently because the scale receives invalid strings from the app. My logs show strange character sequences (like "gggggggggfdhj" or "vfgdddddddddddtty") being sent involuntarily. I haven't programmed these strings, and they cause the scale to terminate the session due to protocol violations. How can I ensure proper socket closure and prevent these random data packets? Additionally, a technical question: Is it possible to keep this TCP connection active in the background indefinitely on iOS while the user interacts with other apps?
3
0
73
2h
Xcode 26.4 and 26.3: Swift compiler crashes during archive with iOS 17 deployment target
I submitted this to Feedback Assistant as FB22331090 and wanted to share a minimal reproducible example here in case others are seeing the same issue. Environment: Xcode 26.4 or Xcode 26.3 Apple Swift version 6.3 (swiftlang-6.3.0.123.5 clang-2100.0.123.102) Effective Swift language version 5.10 Deployment target: iOS 17.0 The sample app builds successfully for normal development use, but archive fails. The crash happens during optimization in EarlyPerfInliner while compiling the synthesized deinit of a nested generic Coordinator class. The coordinator stores a UIHostingController. Minimal reproducer: import SwiftUI struct ReproView<Content: View>: UIViewRepresentable { let content: Content func makeUIView(context: Context) -> UIView { context.coordinator.host.view } func updateUIView(_ uiView: UIView, context: Context) { context.coordinator.host.rootView = content } func makeCoordinator() -> Coordinator { Coordinator(content: content) } final class Coordinator { let host: UIHostingController<Content> init(content: Content) { host = UIHostingController(rootView: content) } } } Used from ContentView like this: ReproView(content: Text("Hello")) Steps: Create a new SwiftUI iOS app. Set deployment target to iOS 17.0. Add the code above. Archive. Expected result: Archive succeeds, or the compiler emits a normal diagnostic. Actual result: The Swift compiler crashes and prints: "Please submit a bug report" "While running pass ... SILFunctionTransform 'EarlyPerfInliner'" The crash occurs while compiling the synthesized deinit for ReproView.Coordinator. Relevant log lines from my archive log: line 209: Please submit a bug report line 215: While running pass ... EarlyPerfInliner line 216: for 'deinit' at ReproView.swift:19:17 One more detail: The same sample archived successfully when the deployment target was higher. Lowering the deployment target to iOS 17.0 made the archive crash reproducible. This may be related to another forum thread about release-only compiler crashes, but the reproducer here is different: this one uses a generic UIViewRepresentable with a nested Coordinator storing UIHostingController.
2
1
164
22h
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.
2
0
122
2d
`ARCamera.unprojectPoint` and `ARCamera.TrackingState` behavior changes between iOS 26.3 and 26.4 under AR resource pressure
ARCamera.TrackingState questions: Did the threshold or sensitivity for transitioning ARCamera.TrackingState from .normal to .limited(.excessiveMotion) or .limited(.insufficientFeatures) change between iOS 26.3 and iOS 26.4? What does "ARWorldTrackingTechnique: resource constraints [33]" mean, and is it new in iOS 26.4? Does it correspond to a tracking state degradation? Is there a way for the client to detect or respond to ARKit entering a resource-constrained mode short of the full tracking state transition — for example, a lower-level notification or a flag on ARFrame — so that apps can take protective action without interpreting it as a full tracking failure? ARCamera.unprojectPoint questions: Did the behavior of ARCamera.unprojectPoint(_:ontoPlane:orientation:viewportSize:) change between iOS 26.3 and iOS 26.4 for near-parallel geometry? Specifically, on iOS 26.3 this method returns nil when the camera ray is nearly parallel to the target plane (denominator of the ray-plane intersection → 0 at ~90° of camera rotation). On iOS 26.4, with identical code and environment, it returns a large finite value instead — we observed z = −12.27m. Since the method's optional return type implies nil is the documented signal for no valid intersection, this reads as a behavioral regression rather than an intentional change. If returning the computed value for near-parallel geometry is now the intended behavior, is there a recommended way for the caller to guard against it? For example, should we check abs(dot(rayDirection, planeNormal)) against a threshold before calling, and if so, is there a documented epsilon Apple uses internally? Alternatively, is there a newer API we should prefer over unprojectPoint(:ontoPlane:) for this use case that handles degenerate geometry more gracefully — such as ARSession.raycast(:)? Are there any other ARKit API adjustments between OS 26.3 and 26.4? We are using the same codebase, but it behaves differently in between these 2 OS versions now. Thanks!
0
0
223
2d
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
204
3d
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
756
4d
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
715
5d
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
67
5d
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
87
5d
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
242
1w
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
418
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
631
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.8k
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
152
2w
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
136
2w
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
962
2w
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
256
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
142
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
2k
Activity
Oct ’25
Issues with TCP Socket Management and Ghost Data on ESP32 (Swift)
Hi everyone, I'm developing an iOS app using Swift (Foundation, Network, and Combine) that communicates via TCP with a weighing scale. The scale uses an internal ESP32 module acting as a Wi-Fi Access Point (no internet access) specifically for data transmission. The app connects to this network and opens a socket to receive weight data and send command strings. I’m currently facing two main issues: Socket Management: The socket isn't closing properly. Occasionally, the app opens multiple simultaneous connections instead of maintaining a single one. Since the ESP32 has a client limit, these ghost connections eventually hang the communication module. Invalid Outbound Data: The connection drops frequently because the scale receives invalid strings from the app. My logs show strange character sequences (like "gggggggggfdhj" or "vfgdddddddddddtty") being sent involuntarily. I haven't programmed these strings, and they cause the scale to terminate the session due to protocol violations. How can I ensure proper socket closure and prevent these random data packets? Additionally, a technical question: Is it possible to keep this TCP connection active in the background indefinitely on iOS while the user interacts with other apps?
Replies
3
Boosts
0
Views
73
Activity
2h
Xcode 26.4 and 26.3: Swift compiler crashes during archive with iOS 17 deployment target
I submitted this to Feedback Assistant as FB22331090 and wanted to share a minimal reproducible example here in case others are seeing the same issue. Environment: Xcode 26.4 or Xcode 26.3 Apple Swift version 6.3 (swiftlang-6.3.0.123.5 clang-2100.0.123.102) Effective Swift language version 5.10 Deployment target: iOS 17.0 The sample app builds successfully for normal development use, but archive fails. The crash happens during optimization in EarlyPerfInliner while compiling the synthesized deinit of a nested generic Coordinator class. The coordinator stores a UIHostingController. Minimal reproducer: import SwiftUI struct ReproView<Content: View>: UIViewRepresentable { let content: Content func makeUIView(context: Context) -> UIView { context.coordinator.host.view } func updateUIView(_ uiView: UIView, context: Context) { context.coordinator.host.rootView = content } func makeCoordinator() -> Coordinator { Coordinator(content: content) } final class Coordinator { let host: UIHostingController<Content> init(content: Content) { host = UIHostingController(rootView: content) } } } Used from ContentView like this: ReproView(content: Text("Hello")) Steps: Create a new SwiftUI iOS app. Set deployment target to iOS 17.0. Add the code above. Archive. Expected result: Archive succeeds, or the compiler emits a normal diagnostic. Actual result: The Swift compiler crashes and prints: "Please submit a bug report" "While running pass ... SILFunctionTransform 'EarlyPerfInliner'" The crash occurs while compiling the synthesized deinit for ReproView.Coordinator. Relevant log lines from my archive log: line 209: Please submit a bug report line 215: While running pass ... EarlyPerfInliner line 216: for 'deinit' at ReproView.swift:19:17 One more detail: The same sample archived successfully when the deployment target was higher. Lowering the deployment target to iOS 17.0 made the archive crash reproducible. This may be related to another forum thread about release-only compiler crashes, but the reproducer here is different: this one uses a generic UIViewRepresentable with a nested Coordinator storing UIHostingController.
Replies
2
Boosts
1
Views
164
Activity
22h
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
2
Boosts
0
Views
122
Activity
2d
`ARCamera.unprojectPoint` and `ARCamera.TrackingState` behavior changes between iOS 26.3 and 26.4 under AR resource pressure
ARCamera.TrackingState questions: Did the threshold or sensitivity for transitioning ARCamera.TrackingState from .normal to .limited(.excessiveMotion) or .limited(.insufficientFeatures) change between iOS 26.3 and iOS 26.4? What does "ARWorldTrackingTechnique: resource constraints [33]" mean, and is it new in iOS 26.4? Does it correspond to a tracking state degradation? Is there a way for the client to detect or respond to ARKit entering a resource-constrained mode short of the full tracking state transition — for example, a lower-level notification or a flag on ARFrame — so that apps can take protective action without interpreting it as a full tracking failure? ARCamera.unprojectPoint questions: Did the behavior of ARCamera.unprojectPoint(_:ontoPlane:orientation:viewportSize:) change between iOS 26.3 and iOS 26.4 for near-parallel geometry? Specifically, on iOS 26.3 this method returns nil when the camera ray is nearly parallel to the target plane (denominator of the ray-plane intersection → 0 at ~90° of camera rotation). On iOS 26.4, with identical code and environment, it returns a large finite value instead — we observed z = −12.27m. Since the method's optional return type implies nil is the documented signal for no valid intersection, this reads as a behavioral regression rather than an intentional change. If returning the computed value for near-parallel geometry is now the intended behavior, is there a recommended way for the caller to guard against it? For example, should we check abs(dot(rayDirection, planeNormal)) against a threshold before calling, and if so, is there a documented epsilon Apple uses internally? Alternatively, is there a newer API we should prefer over unprojectPoint(:ontoPlane:) for this use case that handles degenerate geometry more gracefully — such as ARSession.raycast(:)? Are there any other ARKit API adjustments between OS 26.3 and 26.4? We are using the same codebase, but it behaves differently in between these 2 OS versions now. Thanks!
Replies
0
Boosts
0
Views
223
Activity
2d
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
204
Activity
3d
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
135
Activity
4d
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
756
Activity
4d
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
715
Activity
5d
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
67
Activity
5d
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
87
Activity
5d
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
242
Activity
1w
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
418
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
631
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.8k
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
152
Activity
2w
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
136
Activity
2w
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
962
Activity
2w
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
256
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
142
Activity
2w