Foundation

RSS for tag

Access essential data types, collections, and operating-system services to define the base layer of functionality for your app using Foundation.

Posts under Foundation tag

164 Posts

Post

Replies

Boosts

Views

Activity

Networking Resources
General: Forums subtopic: App & System Services > Networking TN3151 Choosing the right networking API Networking Overview document — Despite the fact that this is in the archive, this is still really useful. TLS for App Developers forums post Choosing a Network Debugging Tool documentation WWDC 2019 Session 712 Advances in Networking, Part 1 — This explains the concept of constrained networking, which is Apple’s preferred solution to questions like How do I check whether I’m on Wi-Fi? TN3135 Low-level networking on watchOS TN3179 Understanding local network privacy Adapt to changing network conditions tech talk TCP and UDP ports used by Apple software products support article Understanding Also-Ran Connections forums post Extra-ordinary Networking forums post Foundation networking: Forums tags: Foundation, CFNetwork URL Loading System documentation — NSURLSession, or URLSession in Swift, is the recommended API for HTTP[S] on Apple platforms. Moving to Fewer, Larger Transfers forums post Testing Background Session Code forums post Network framework: Forums tag: Network Network framework documentation — Network framework is the recommended API for TCP, UDP, and QUIC on Apple platforms. Building a custom peer-to-peer protocol sample code (aka TicTacToe) Implementing netcat with Network Framework sample code (aka nwcat) Configuring a Wi-Fi accessory to join a network sample code Moving from Multipeer Connectivity to Network Framework forums post NWEndpoint History and Advice forums post Wi-Fi (general): How to modernize your captive network developer news post Wi-Fi Fundamentals forums post Filing a Wi-Fi Bug Report forums post Working with a Wi-Fi Accessory forums post — This is part of the Extra-ordinary Networking series. Wi-Fi (iOS): TN3111 iOS Wi-Fi API overview technote Wi-Fi Aware framework documentation WirelessInsights framework documentation iOS Network Signal Strength forums post Network Extension Resources Wi-Fi on macOS: Forums tag: Core WLAN Core WLAN framework documentation Secure networking: Forums tags: Security Apple Platform Security support document Preventing Insecure Network Connections documentation — This is all about App Transport Security (ATS). WWDC 2017 Session 701 Your Apps and Evolving Network Security Standards [1] — This is generally interesting, but the section starting at 17:40 is, AFAIK, the best information from Apple about how certificate revocation works on modern systems. WWDC 2025 Session 314 Get ahead with quantum-secure cryptography Available trusted root certificates for Apple operating systems support article Requirements for trusted certificates in iOS 13 and macOS 10.15 support article About upcoming limits on trusted certificates support article Apple’s Certificate Transparency policy support article What’s new for enterprise in iOS 18 support article — This discusses new key usage requirements. Prepare your network environment for stricter security requirements support article — This is primarily of interest to folks developing management software, for example, an MDM server. Technote 2232 HTTPS Server Trust Evaluation Technote 2326 Creating Certificates for TLS Testing QA1948 HTTPS and Test Servers Miscellaneous: More network-related forums tags: 5G, QUIC, Bonjour On FTP forums post Using the Multicast Networking Additional Capability forums post Investigating Network Latency Problems forums post Share and Enjoy — Quinn “The Eskimo!” @ Developer Technical Support @ Apple let myEmail = "eskimo" + "1" + "@" + "apple.com" [1] This video is no longer available from Apple, but the URL should help you locate other sources of this info.
0
0
4.8k
May ’26
Does NI now support DIRECTION finding for UWB in more recent iPhone models?
Given that Apple is a Sponsor level member of the FIRa Consortium (on UWB interoperability) and the FIRa 3.0 spec has been released, are there any improvements in the Nearby Interaction framework for UWB direction tracking? It appears that NI returns null for direction-found with third-party UWB device currently.
0
0
29
3d
Approaching Custom VST GUI Automation: Combining local Vision OCR with the new FoundationModels framework for screen-grounding
Hello everyone, I’m working on a project to automate software controls inside non-standard macOS applications—specifically custom-drawn audio plugins (like the Roland TR-909 VST). The Challenge: These VST interfaces do not expose their buttons, knobs, or dials via the standard macOS Accessibility tree (NSAccessibility / event taps). Because they are custom-rendered, standard automation tools are blind to them. My Current Hybrid Approach: I am combining two of Apple's local machine learning technologies to solve this without sending data to the cloud: Step 1: Text-Based Layout Mapping (Vision Framework) I capture a screenshot of the targeted window using Quartz Window Services and run a local VNRecognizeTextRequest to extract coordinates for all text labels. This works exceptionally well for text buttons like "OPTION" or "ABOUT". Step 2: Contextual & Non-Text Element Interpretation (FoundationModels Framework) For controls that lack text labels (such as blank step sequencer buttons, parameter knobs, or toggle light states), I pass the screenshot as an Attachment into the new local LanguageModelSession. I ask the model to ground coordinates relative to the text landmarks mapped in Step 1. Here is a simplified snippet of how I am feeding the visual context into the local model: import Foundation import FoundationModels import Cocoa func analyzePluginInterface(cgImage: CGImage) async { guard SystemLanguageModel.default.isAvailable else { print("Local model not downloaded or available.") return } let instructions = """ You are a screen-aware assistant. Your job is to locate GUI controls on a custom 1024x802 VST window. """ let session = LanguageModelSession(instructions: instructions) do { let response = try await session.respond { "Look at this screenshot of the VST window." Attachment(cgImage) "Locate the blank step-sequencer buttons located below the instrument channel labels." "What are the center coordinates (X, Y) for the first active step?" } print("Model Grounding Output: \(response.content)") } catch { print("Inference failed: \(error)") } } My Questions for the Community: Performance & Latency: The local LanguageModelSession.respond call takes several seconds to run on device. For real-time DAW automation, this is a bottleneck. Has anyone experimented with using a custom LoRA adapter or a smaller model profile to speed up spatial coordinate inference? Coordinate Stability: Multimodal models can sometimes hallucinate coordinates (bounding box values). What strategies are you using to constrain the model output to precise pixel boundaries on varying display scaling configurations (Retina vs non-Retina)? Alternative Solutions: Are there newer on-device vision APIs (perhaps in CoreML or Vision) that are better suited for bounding-box grounding of abstract graphics (like dials/knobs) than a general language model session? Would love to hear how others are approaching screen-aware GUI interpretation with these new frameworks! Thanks!
0
0
30
3d
Maps for specific type of car
Hi there, I am currently developing an app for a specific type of car that cannot/is not allowed to drive everywhere in the Netherlands. I know there is a feature for avoiding highways. However, this is not enough. It also involves a special sign that, once the driver sees it, prevents them from driving any further. My question is: Is there an API I can use to properly develop this? I look forward to your response(s). Regards, Sebastiaan
0
0
21
3d
Customer support is not responding me!!!
Why don't you answer me? Why don't you solve my problem? I want to escalate my request. Who should I contact to escalate the issue? You're not answering my questions. I am a law-abiding citizen, I have a huge amount of apple equipment, which I officially bought. I spend money on all subscriptions and am a long-time apple user. And you treat me so badly!!! I have a problem with enrollment process. i want to get a developer account and i can't do it more then 1 month. it is so badly experience.
0
1
58
3d
URLSession on watchOS never fails over to watch's own Wi-Fi when paired iPhone has Bluetooth but no internet (-1200)
We develop a healthcare emergency-alerting app with a native watchOS companion app. We've hit a network routing issue on watchOS that we cannot work around with any public API, and it breaks a safety-critical flow (triggering an emergency alarm from the watch). Environment watchOS 26.5 on Apple Watch SE3, paired with iPhone SE on iOS 26.5 Watch app deployment target: watchOS 9.0 Plain URLSession (async/await), default configuration plus waitsForConnectivity = false, allowsExpensiveNetworkAccess = true, allowsConstrainedNetworkAccess = true HTTPS to our own backend (valid public TLS certificate, no pinning) Steps to reproduce Pair the watch with the iPhone. Both on the same known Wi-Fi network. On the iPhone: turn OFF Wi-Fi and cellular data. Keep Bluetooth ON. The watch remains connected to its known Wi-Fi network (or would be, if the system brought the radio up). Trigger any HTTPS request from the watch app (foreground). Expected Since the companion iPhone has no internet, the watch should satisfy the request over its own Wi-Fi. Actual The request is routed through the companion link (ipsec1, "companion preference: prefer" in the logs) and fails after the TLS handshake dies inside the tunnel: Error Domain=NSURLErrorDomain Code=-1200 "An SSL error has occurred and a secure connection to the server cannot be made." _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9816 (errSSLClosedNoNotify) The watch never fails over to its own Wi-Fi, no matter how many times we retry or how long we wait. The same request succeeds within seconds if the user disables Bluetooth on the iPhone (watch then joins Wi-Fi directly), or restores the iPhone's internet. What we already tried waitsForConnectivity = true doesn't help; a path exists (the tunnel), it just doesn't work. Fresh URLSession per retry, backoff retries still routed via the tunnel. Per TN3135 we understand low-level networking is not available to a normal app: we prototyped NWConnection with prohibitedInterfaceTypes = [.other], and indeed on device NWPathMonitor stays .unsatisfied even when the watch has working Wi-Fi, exactly as TN3135 describes. So Network framework is not an escape hatch for us, and we are not looking to abuse the audio-streaming/CallKit carve-outs. Questions Is the companion-preferred routing supposed to fail over to the watch's own Wi-Fi when the iPhone is reachable over Bluetooth but has no internet? If yes, on what timescale, and is there anything an app can do to help the system notice the dead path sooner? Is there ANY supported way for a foreground watchOS app to express "do not use the companion link for this request"? We found only the private _companionProxyPreference SPI, which we obviously can't ship. If the answer to both is "no", what is the recommended pattern for safety-critical requests in this state is failing fast and instructing the user to disable iPhone Bluetooth really the intended UX? Related earlier reports of the same behavior: https://developer.apple.com/forums/thread/759321 https://developer.apple.com/forums/thread/107964
1
0
62
4d
NSFilePresenter primaryPresentedItemURL
There is an API in NSFilePresenter called primaryPresentedItemURL. It is implemented on macOS, but not iOS or Catalyst. I want to use it to write an XMP sidecar file next to original image files. However, because it’s not implemented on iOS or Catalyst, I cannot do this. The only workaround I have found is to ask the user for access to the whole folder. This, of course, is bad from a user privacy / security standpoint, especially as it gives the app access not only to the folder contents, but all subfolders. Can you give me a better workaround, or implement the API on iOS and Catalyst? Feedback Number is FB22771292
3
0
121
4d
Screen Reader for macOS implemented with Swift Concurrency and Distributed Actors
Repurposing my questions that weren't a good fit for the group lab to see how that goes :) I've been building a ScreenReader in Swift leveraging Structured Concurrency, actors, and recently distributed actors over XPC. https://codeberg.org/SpeakUp I have a number of questions I could ask (and would love to ask) but would start with asking for thoughts on my RunLoopExecutor project https://codeberg.org/SpeakUp/RunLoopExecutor/ All of the macOS Accessibility APIs are C/CoreFoundation/CFRunLoop based and I wanted to build something where actors would feel idiomatic for an experienced Swift developer but under the hood we're making sure that we're not contending with ourselves with all the IPC we're doing to get Accessibility data. I think so far it's been pretty successful as seen in the Controller types for the ScreenReader project: https://codeberg.org/SpeakUp/ScreenReader I'm currently using pretty naive pool implementations, one that is fixed width and one that is dynamic with a maximum width. Would love to hear different approaches to growing and shrinking the thread pool and handling things like marking a given executor as likely in a bad state (usually meaning the app it's talking to over AX API is blocking it's main thread) In the AccessibilityElement project https://codeberg.org/SpeakUp/AccessibilityElement for my HIServices Observer implementation I'm exposed to a race condition where axobserver doesn't flush it's notification queue on remove. I'm relying on pthread_specific currently to introduce thread local storage to work around this but it's quite clunky. In an ideal world the HIServices API would emit a done event to allow cleanup but so far that hasn't happened. I'll leave it there for now and do new posts with more requests for feedback if this one is well received.
2
0
111
4d
URLSession on watchOS never fails over to watch's own Wi-Fi when paired iPhone has Bluetooth but no internet (-1200)
We develop a healthcare emergency-alerting app with a native watchOS companion app. We've hit a network routing issue on watchOS that we cannot work around with any public API, and it breaks a safety-critical flow (triggering an emergency alarm from the watch). Environment watchOS 26.5 on Apple Watch SE3, paired with iPhone SE 2nd Gen on iOS 26.5 Watch app deployment target: watchOS 9.0 Plain URLSession (async/await), default configuration plus waitsForConnectivity = false, allowsExpensiveNetworkAccess = true, allowsConstrainedNetworkAccess = true HTTPS to our own backend (valid public TLS certificate, no pinning) Steps to reproduce Pair the watch with the iPhone. Both on the same known Wi-Fi network. On the iPhone: turn OFF Wi-Fi and cellular data. Keep Bluetooth ON. The watch remains connected to its known Wi-Fi network (or would be, if the system brought the radio up). Trigger any HTTPS request from the watch app (foreground). Expected Since the companion iPhone has no internet, the watch should satisfy the request over its own Wi-Fi. Actual The request is routed through the companion link (ipsec1, "companion preference: prefer" in the logs) and fails after the TLS handshake dies inside the tunnel: Error Domain=NSURLErrorDomain Code=-1200 "An SSL error has occurred and a secure connection to the server cannot be made." _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9816 (errSSLClosedNoNotify) The watch never fails over to its own Wi-Fi, no matter how many times we retry or how long we wait. The same request succeeds within seconds if the user disables Bluetooth on the iPhone (watch then joins Wi-Fi directly), or restores the iPhone's internet. What we already tried waitsForConnectivity = true doesn't help; a path exists (the tunnel), it just doesn't work. Fresh URLSession per retry, backoff retries still routed via the tunnel. Per TN3135 we understand low-level networking is not available to a normal app: we prototyped NWConnection with prohibitedInterfaceTypes = [.other], and indeed on device NWPathMonitor stays .unsatisfied even when the watch has working Wi-Fi, exactly as TN3135 describes. So Network framework is not an escape hatch for us, and we are not looking to abuse the audio-streaming/CallKit carve-outs. Questions Is the companion-preferred routing supposed to fail over to the watch's own Wi-Fi when the iPhone is reachable over Bluetooth but has no internet? If yes, on what timescale, and is there anything an app can do to help the system notice the dead path sooner? Is there ANY supported way for a foreground watchOS app to express "do not use the companion link for this request"? We found only the private _companionProxyPreference SPI, which we obviously can't ship. If the answer to both is "no", what is the recommended pattern for safety-critical requests in this state is failing fast and instructing the user to disable iPhone Bluetooth really the intended UX? Related earlier reports of the same behavior: https://developer.apple.com/forums/thread/759321 https://developer.apple.com/forums/thread/107964
0
0
46
4d
Which storage capacity key should be used for offline video downloads: volumeAvailableCapacityKey or volumeAvailableCapacityForImportantUsageKey?
I’m trying to understand which storage capacity key is the correct one to use when deciding whether my app can start downloading offline video content. I read the documentation here: https://developer.apple.com/documentation/foundation/checking-volume-storage-capacity but I still don’t fully understand the intended usage difference between: volumeAvailableCapacityKey volumeAvailableCapacityForImportantUsageKey My app allows users to download videos for offline viewing. These downloads may remain on the device for a long time (days or even months), so they are not just temporary cache files. On one hand, this seems to match the description of “storing data based on a user request”, which suggests using volumeAvailableCapacityForImportantUsageKey. On the other hand, my understanding is that this value may assume the system is willing to aggressively purge caches and reclaim space for this “important usage”. I’m worried this could lead to unexpected or unpleasant side effects for the user if my app relies on that space. What confuses me even more is that the values are significantly different on my device: iPhone Settings reports about 142 GB free volumeAvailableCapacityKey returns only ~56 GB volumeAvailableCapacityForImportantUsageKey returns ~132 GB So my question is: For an app that downloads videos for offline playback — where the user explicitly requested the download, but the content may stay on device for a long time — which value is the recommended one to use when deciding whether there is enough free space to start the download? Should offline media downloads generally be treated as “important usage” in the sense intended by this API?
3
0
626
3w
-startDownloadingUbiquitousItemAtURL:error: and NSURLUbiquitousItemDownloadRequestedKey
I'm trying to update the iCloud data handling in our app, and I'm running into an issue with a particular file on one particular device. This file never downloads & I haven't been able to pinpoint what's off about it. Right now we just have 2 iCloud accounts & a handful of devices, so I haven't been able to narrow it down yet, but in most cases, all the cloud files download as expected. However, whether or not the file eventually downloads, the NSURLUbiquitousItemDownloadRequestedKey key seems to be completely useless. For the following code: NSError *error = nil; BOOL success = [[NSFileManager defaultManager] startDownloadingUbiquitousItemAtURL:self.fileURL error:&error]; if (!success) { NSLog(@"error downloading %@ : %@", self.fileURL, error); } else { NSDictionary *resourceValues = [self.fileURL resourceValuesForKeys:@[NSURLUbiquitousItemDownloadRequestedKey, NSURLUbiquitousItemIsDownloadingKey, NSURLUbiquitousItemDownloadingErrorKey, NSURLUbiquitousItemDownloadingStatusKey] error:&error]; if (!error) { NSString *downloadStatus = resourceValues[NSURLUbiquitousItemDownloadingStatusKey]; bool downloadRequested = [resourceValues[NSURLUbiquitousItemDownloadRequestedKey] boolValue]; NSLog(@"download requested: %d", downloadRequested); } // ... } downloadRequested is always false, regardless of whether or not the cloud file eventually downloads. I have 2 questions: is there a way to actually check if a download has been requested for a file? what could be preventing this file from downloading? -startDownloadingUbiquitousItemAtURL:error: doesn't report an error, NSURLUbiquitousItemDownloadingErrorKey is always nil, and no error is reported in the NSMetadataQuery observer.
4
0
482
3w
concurrent downloading of files with URLSession downloadTask with background configuration.
According to documentation, the URLSession background tasks continue even when the app is suspended. What is the lifespan of the URLSessionDownloadDelegate object when app is suspended or terminated? Will it get re-created and re-initialize properties when the app re-launches, or will it somehow restore the existing property values? Also, urlSessionDidFinishEvents not getting called, and what do we need to do there with the backgroundCompletionHandler? Any insights are much appreciated. We are getting ready to launch and this is a roadblock. (visionOS26.4) Thank you. @Observable class DownloadManager: NSObject, URLSessionDownloadDelegate { ... let config = URLSessionConfiguration.background(withIdentifier: "TestDL") config.sessionSendsLaunchEvents = true var urlSession = URLSession(configuration: config, delegate: self, delegateQueue: nil) func downloadFiles(... { // initiate multiple file downloads concurrently for url in urlList { let task = urlSession.downloadTask(with: url) task.resume() } } func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { ... func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { ... func urlSession(_: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { ... // Not getting called ?? // Is this only called when app is suspended/terminated? func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) { print("didFinishEvents") Task { @MainActor in //urlSession?.finishTasksAndInvalidate() //urlSession = nil // not sure what to do here: if let appDelegate = UIApplication.shared.delegate as? AppDelegate, let completionHandler = appDelegate.backgroundCompletionHandler { completionHandler() appDelegate.backgroundCompletionHandler = nil } } }
5
0
729
May ’26
[iOS 26.x] WKWebView crashes with NSInternalInconsistencyException — KVO inconsistency on configuration.enforcesChildRestrictions from STScreenTimeConfigurationObserver
Summary We are seeing a recurring fatal NSInternalInconsistencyException on iOS 26.x devices. The crash originates entirely from system frameworks (Foundation / WebKit / Screen Time / NSXPCConnection) — there are no app frames in the stack. The exception is raised from an XPC reply on a worker thread, so the host app cannot wrap it in @try/@catch. The crash appears to be a KVO consistency check failing inside the platform's internal Screen Time observer (STScreenTimeConfigurationObserver) when it observes WKWebView's configuration.enforcesChildRestrictions key path. The exception message states the value of the intermediate key configuration changed without an appropriate KVO notification. Environment iOS versions: 26.2.1 (also seen on 26.0.x – 26.2.x) Devices: iPhone 13 (iPhone14,5), iPhone 16 Plus, others App orientation: portrait Process state at crash: BACKGROUND (most occurrences) App uses WKWebView in several screens (link preview, in-app web, 3rd-party SDK web views) Crash is recurring across multiple users on iOS 26.x and is reproducible at scale in production Exception Name: NSInternalInconsistencyException Reason: Cannot update for observer <WKScreenTimeConfigurationObserver 0x...> for the key path "configuration.enforcesChildRestrictions" from <STScreenTimeConfigurationObserver 0x...>, most likely because the value for the key "configuration" has changed without an appropriate KVO notification being sent. Check the KVO-compliance of the STScreenTimeConfigurationObserver class. Crashing thread (top frames) 0 CoreFoundation __exceptionPreprocess 1 libobjc.A.dylib objc_exception_throw 2 Foundation -[NSKeyValueNestedProperty object:withObservance:didChangeValueForKeyOrKeys:recurse:forwardingValues:] 3 Foundation NSKeyValueDidChange 4 Foundation -[NSObject(NSKeyValueObservingPrivate) _changeValueForKeys:count:maybeOldValuesDict:maybeNewValuesDict:usingBlock:] 5 Foundation -[NSObject(NSKeyValueObservingPrivate) _changeValueForKey:key:key:usingBlock:] 6 Foundation NSSetObjectValueAndNotify 7 CoreFoundation invoking 8 Foundation -[NSInvocation invoke] 9 Foundation 10 Foundation -[NSXPCConnection _decodeAndInvokeReplyBlockWithEvent:sequence:replyInfo:] 11 Foundation __88-[NSXPCConnection _sendInvocation:orArguments:count:methodSignature:selector:withProxy:]_block_invoke_5 12 libxpc.dylib _xpc_connection_reply_callout 13 libxpc.dylib _xpc_connection_call_reply_async 14 libdispatch.dylib _dispatch_mach_msg_async_reply_invoke 15 libdispatch.dylib _dispatch_root_queue_drain_deferred_item 16 libdispatch.dylib _dispatch_kevent_worker_thread (Every frame above frame 0 lives in the system. No app frames are present.) What we observed Crash fires asynchronously on a libdispatch kevent worker thread, triggered by an XPC reply from the Screen Time service. The exception is thrown while the platform updates a chained KVO key path (configuration.enforcesChildRestrictions) on a WKWebView instance. The intermediate key configuration apparently changed without a paired willChange/didChange notification, which Foundation's KVO machinery then flags as inconsistency. Because the throw happens on the XPC reply path, there is no app-level synchronous frame we can wrap to recover. The exception unwinds straight into std::__terminate. What we tried (no effect) Confirmed all WKWebView creation and release happens on the main thread. Stop loading and nil out navigationDelegate before releasing the WKWebView. Avoided mutating WKWebViewConfiguration after the WKWebView is created. Checked for any custom KVO on WKWebView.configuration in app code — none exists. The crash still reproduces; we have no path to mitigate it from the application side. Questions for Apple / the community Is STScreenTimeConfigurationObserver expected to observe WKWebView.configuration.enforcesChildRestrictions under all conditions on iOS 26, or only when Screen Time / Communication Limits / Child Restrictions are enabled on the device? 2. Is there a public API (WKWebViewConfiguration option, Info.plist key, etc.) to opt a WKWebView out of Screen Time observation for hosts that do not need Screen Time integration for their web content? 3. Is this a known regression in iOS 26.x KVO chained-key-path notification posting inside WebKit's Screen Time integration? If so, is a fix slated for an upcoming 26.x release? 4. Is there any recommended workaround on the application side that does not rely on swizzling private Foundation / NSXPCConnection methods? Reproduction notes We do not have a deterministic local repro. Crashes are heavily concentrated on: iOS 26.2.1 Devices with Screen Time / Communication Limits / Child Restrictions configured at the OS level App entering the BACKGROUND state shortly after a WKWebView session If anyone has a reliable local repro on a developer device, please share — we would also like to file a Feedback Assistant report with steps. Filed Feedback Will attach FB number once filed. Thanks in advance.
1
0
948
May ’26
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
619
May ’26
NSURLSession background downloadTasks sometimes calling urlSession(_:downloadTask:didFinishDownloadingTo:) *twice*
I've just implemented background session downloads, and in testing (with 1044 downloadTasks), I'm seeing some strange behavior that's not 100% reproducible. Sometimes when I background the app, when I foreground it (or the OS does), the URLSessionDownloadDelegate's function urlSession(_:downloadTask:didFinishDownloadingTo:) gets called twice. I'm also logging the URLSessionTaskDelegate's function urlSession(_:task:didCompleteWithError:) and in this case, it does not get called between calls to didFinishDownloadingTo. Both cases are being called with the exactly same task, session and location. The first call copies the location to a semi-permanent destination (and I confirmed that file is correct), and the second call fails on move because the destination already exists. I can obviously work around this fairly easily, but wondering if I'm missing something or if there's a bug. It does appear to happen more reliably when I background for 15 seconds or longer. A second issue which is reproducible is that while backgrounded, some files are completing downloads and never calling the download delegate's urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:) I tried resuming one or all of the tasks in applicationDidBecomeActive as suggested in multiple other forums posts, but neither of those seems to resolve the issue. Again, I can work around this (using a combination of totalBytesWritten and the known size of files which have completed downloads), but I'm wondering if I'm missing something obvious. I actually thought that perhaps the resume() workaround was causing the first issue, but removing it does not have an effect.
8
0
2.1k
May ’26
Networking Resources
General: Forums subtopic: App & System Services > Networking TN3151 Choosing the right networking API Networking Overview document — Despite the fact that this is in the archive, this is still really useful. TLS for App Developers forums post Choosing a Network Debugging Tool documentation WWDC 2019 Session 712 Advances in Networking, Part 1 — This explains the concept of constrained networking, which is Apple’s preferred solution to questions like How do I check whether I’m on Wi-Fi? TN3135 Low-level networking on watchOS TN3179 Understanding local network privacy Adapt to changing network conditions tech talk TCP and UDP ports used by Apple software products support article Understanding Also-Ran Connections forums post Extra-ordinary Networking forums post Foundation networking: Forums tags: Foundation, CFNetwork URL Loading System documentation — NSURLSession, or URLSession in Swift, is the recommended API for HTTP[S] on Apple platforms. Moving to Fewer, Larger Transfers forums post Testing Background Session Code forums post Network framework: Forums tag: Network Network framework documentation — Network framework is the recommended API for TCP, UDP, and QUIC on Apple platforms. Building a custom peer-to-peer protocol sample code (aka TicTacToe) Implementing netcat with Network Framework sample code (aka nwcat) Configuring a Wi-Fi accessory to join a network sample code Moving from Multipeer Connectivity to Network Framework forums post NWEndpoint History and Advice forums post Wi-Fi (general): How to modernize your captive network developer news post Wi-Fi Fundamentals forums post Filing a Wi-Fi Bug Report forums post Working with a Wi-Fi Accessory forums post — This is part of the Extra-ordinary Networking series. Wi-Fi (iOS): TN3111 iOS Wi-Fi API overview technote Wi-Fi Aware framework documentation WirelessInsights framework documentation iOS Network Signal Strength forums post Network Extension Resources Wi-Fi on macOS: Forums tag: Core WLAN Core WLAN framework documentation Secure networking: Forums tags: Security Apple Platform Security support document Preventing Insecure Network Connections documentation — This is all about App Transport Security (ATS). WWDC 2017 Session 701 Your Apps and Evolving Network Security Standards [1] — This is generally interesting, but the section starting at 17:40 is, AFAIK, the best information from Apple about how certificate revocation works on modern systems. WWDC 2025 Session 314 Get ahead with quantum-secure cryptography Available trusted root certificates for Apple operating systems support article Requirements for trusted certificates in iOS 13 and macOS 10.15 support article About upcoming limits on trusted certificates support article Apple’s Certificate Transparency policy support article What’s new for enterprise in iOS 18 support article — This discusses new key usage requirements. Prepare your network environment for stricter security requirements support article — This is primarily of interest to folks developing management software, for example, an MDM server. Technote 2232 HTTPS Server Trust Evaluation Technote 2326 Creating Certificates for TLS Testing QA1948 HTTPS and Test Servers Miscellaneous: More network-related forums tags: 5G, QUIC, Bonjour On FTP forums post Using the Multicast Networking Additional Capability forums post Investigating Network Latency Problems forums post Share and Enjoy — Quinn “The Eskimo!” @ Developer Technical Support @ Apple let myEmail = "eskimo" + "1" + "@" + "apple.com" [1] This video is no longer available from Apple, but the URL should help you locate other sources of this info.
Replies
0
Boosts
0
Views
4.8k
Activity
May ’26
RAG support
What kind out-of-box on-device RAG support exists in the foundation models framework? (vector DBs, embedding methods etc., agentic RAG hooks?)
Replies
0
Boosts
0
Views
17
Activity
3d
Does NI now support DIRECTION finding for UWB in more recent iPhone models?
Given that Apple is a Sponsor level member of the FIRa Consortium (on UWB interoperability) and the FIRa 3.0 spec has been released, are there any improvements in the Nearby Interaction framework for UWB direction tracking? It appears that NI returns null for direction-found with third-party UWB device currently.
Replies
0
Boosts
0
Views
29
Activity
3d
Approaching Custom VST GUI Automation: Combining local Vision OCR with the new FoundationModels framework for screen-grounding
Hello everyone, I’m working on a project to automate software controls inside non-standard macOS applications—specifically custom-drawn audio plugins (like the Roland TR-909 VST). The Challenge: These VST interfaces do not expose their buttons, knobs, or dials via the standard macOS Accessibility tree (NSAccessibility / event taps). Because they are custom-rendered, standard automation tools are blind to them. My Current Hybrid Approach: I am combining two of Apple's local machine learning technologies to solve this without sending data to the cloud: Step 1: Text-Based Layout Mapping (Vision Framework) I capture a screenshot of the targeted window using Quartz Window Services and run a local VNRecognizeTextRequest to extract coordinates for all text labels. This works exceptionally well for text buttons like "OPTION" or "ABOUT". Step 2: Contextual & Non-Text Element Interpretation (FoundationModels Framework) For controls that lack text labels (such as blank step sequencer buttons, parameter knobs, or toggle light states), I pass the screenshot as an Attachment into the new local LanguageModelSession. I ask the model to ground coordinates relative to the text landmarks mapped in Step 1. Here is a simplified snippet of how I am feeding the visual context into the local model: import Foundation import FoundationModels import Cocoa func analyzePluginInterface(cgImage: CGImage) async { guard SystemLanguageModel.default.isAvailable else { print("Local model not downloaded or available.") return } let instructions = """ You are a screen-aware assistant. Your job is to locate GUI controls on a custom 1024x802 VST window. """ let session = LanguageModelSession(instructions: instructions) do { let response = try await session.respond { "Look at this screenshot of the VST window." Attachment(cgImage) "Locate the blank step-sequencer buttons located below the instrument channel labels." "What are the center coordinates (X, Y) for the first active step?" } print("Model Grounding Output: \(response.content)") } catch { print("Inference failed: \(error)") } } My Questions for the Community: Performance & Latency: The local LanguageModelSession.respond call takes several seconds to run on device. For real-time DAW automation, this is a bottleneck. Has anyone experimented with using a custom LoRA adapter or a smaller model profile to speed up spatial coordinate inference? Coordinate Stability: Multimodal models can sometimes hallucinate coordinates (bounding box values). What strategies are you using to constrain the model output to precise pixel boundaries on varying display scaling configurations (Retina vs non-Retina)? Alternative Solutions: Are there newer on-device vision APIs (perhaps in CoreML or Vision) that are better suited for bounding-box grounding of abstract graphics (like dials/knobs) than a general language model session? Would love to hear how others are approaching screen-aware GUI interpretation with these new frameworks! Thanks!
Replies
0
Boosts
0
Views
30
Activity
3d
Maps for specific type of car
Hi there, I am currently developing an app for a specific type of car that cannot/is not allowed to drive everywhere in the Netherlands. I know there is a feature for avoiding highways. However, this is not enough. It also involves a special sign that, once the driver sees it, prevents them from driving any further. My question is: Is there an API I can use to properly develop this? I look forward to your response(s). Regards, Sebastiaan
Replies
0
Boosts
0
Views
21
Activity
3d
Customer support is not responding me!!!
Why don't you answer me? Why don't you solve my problem? I want to escalate my request. Who should I contact to escalate the issue? You're not answering my questions. I am a law-abiding citizen, I have a huge amount of apple equipment, which I officially bought. I spend money on all subscriptions and am a long-time apple user. And you treat me so badly!!! I have a problem with enrollment process. i want to get a developer account and i can't do it more then 1 month. it is so badly experience.
Replies
0
Boosts
1
Views
58
Activity
3d
Fallas de conexión y perdida de datos
Falla de enlace con apple watch estando blueetooth y wifi activados reloj quedando en bucle de inicio, iphone con perdida de enlace airpord s brillo baja o sube VM virtal
Replies
0
Boosts
0
Views
44
Activity
3d
URLSession on watchOS never fails over to watch's own Wi-Fi when paired iPhone has Bluetooth but no internet (-1200)
We develop a healthcare emergency-alerting app with a native watchOS companion app. We've hit a network routing issue on watchOS that we cannot work around with any public API, and it breaks a safety-critical flow (triggering an emergency alarm from the watch). Environment watchOS 26.5 on Apple Watch SE3, paired with iPhone SE on iOS 26.5 Watch app deployment target: watchOS 9.0 Plain URLSession (async/await), default configuration plus waitsForConnectivity = false, allowsExpensiveNetworkAccess = true, allowsConstrainedNetworkAccess = true HTTPS to our own backend (valid public TLS certificate, no pinning) Steps to reproduce Pair the watch with the iPhone. Both on the same known Wi-Fi network. On the iPhone: turn OFF Wi-Fi and cellular data. Keep Bluetooth ON. The watch remains connected to its known Wi-Fi network (or would be, if the system brought the radio up). Trigger any HTTPS request from the watch app (foreground). Expected Since the companion iPhone has no internet, the watch should satisfy the request over its own Wi-Fi. Actual The request is routed through the companion link (ipsec1, "companion preference: prefer" in the logs) and fails after the TLS handshake dies inside the tunnel: Error Domain=NSURLErrorDomain Code=-1200 "An SSL error has occurred and a secure connection to the server cannot be made." _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9816 (errSSLClosedNoNotify) The watch never fails over to its own Wi-Fi, no matter how many times we retry or how long we wait. The same request succeeds within seconds if the user disables Bluetooth on the iPhone (watch then joins Wi-Fi directly), or restores the iPhone's internet. What we already tried waitsForConnectivity = true doesn't help; a path exists (the tunnel), it just doesn't work. Fresh URLSession per retry, backoff retries still routed via the tunnel. Per TN3135 we understand low-level networking is not available to a normal app: we prototyped NWConnection with prohibitedInterfaceTypes = [.other], and indeed on device NWPathMonitor stays .unsatisfied even when the watch has working Wi-Fi, exactly as TN3135 describes. So Network framework is not an escape hatch for us, and we are not looking to abuse the audio-streaming/CallKit carve-outs. Questions Is the companion-preferred routing supposed to fail over to the watch's own Wi-Fi when the iPhone is reachable over Bluetooth but has no internet? If yes, on what timescale, and is there anything an app can do to help the system notice the dead path sooner? Is there ANY supported way for a foreground watchOS app to express "do not use the companion link for this request"? We found only the private _companionProxyPreference SPI, which we obviously can't ship. If the answer to both is "no", what is the recommended pattern for safety-critical requests in this state is failing fast and instructing the user to disable iPhone Bluetooth really the intended UX? Related earlier reports of the same behavior: https://developer.apple.com/forums/thread/759321 https://developer.apple.com/forums/thread/107964
Replies
1
Boosts
0
Views
62
Activity
4d
NSFilePresenter primaryPresentedItemURL
There is an API in NSFilePresenter called primaryPresentedItemURL. It is implemented on macOS, but not iOS or Catalyst. I want to use it to write an XMP sidecar file next to original image files. However, because it’s not implemented on iOS or Catalyst, I cannot do this. The only workaround I have found is to ask the user for access to the whole folder. This, of course, is bad from a user privacy / security standpoint, especially as it gives the app access not only to the folder contents, but all subfolders. Can you give me a better workaround, or implement the API on iOS and Catalyst? Feedback Number is FB22771292
Replies
3
Boosts
0
Views
121
Activity
4d
Screen Reader for macOS implemented with Swift Concurrency and Distributed Actors
Repurposing my questions that weren't a good fit for the group lab to see how that goes :) I've been building a ScreenReader in Swift leveraging Structured Concurrency, actors, and recently distributed actors over XPC. https://codeberg.org/SpeakUp I have a number of questions I could ask (and would love to ask) but would start with asking for thoughts on my RunLoopExecutor project https://codeberg.org/SpeakUp/RunLoopExecutor/ All of the macOS Accessibility APIs are C/CoreFoundation/CFRunLoop based and I wanted to build something where actors would feel idiomatic for an experienced Swift developer but under the hood we're making sure that we're not contending with ourselves with all the IPC we're doing to get Accessibility data. I think so far it's been pretty successful as seen in the Controller types for the ScreenReader project: https://codeberg.org/SpeakUp/ScreenReader I'm currently using pretty naive pool implementations, one that is fixed width and one that is dynamic with a maximum width. Would love to hear different approaches to growing and shrinking the thread pool and handling things like marking a given executor as likely in a bad state (usually meaning the app it's talking to over AX API is blocking it's main thread) In the AccessibilityElement project https://codeberg.org/SpeakUp/AccessibilityElement for my HIServices Observer implementation I'm exposed to a race condition where axobserver doesn't flush it's notification queue on remove. I'm relying on pthread_specific currently to introduce thread local storage to work around this but it's quite clunky. In an ideal world the HIServices API would emit a done event to allow cleanup but so far that hasn't happened. I'll leave it there for now and do new posts with more requests for feedback if this one is well received.
Replies
2
Boosts
0
Views
111
Activity
4d
documentIdentifierKey description
What is URLResourceKey.documentIdentifierKey intended to identify compared with fileIdentifierKey? Is it expected to persist across save/replace operations, rename, move, app relaunch, or unmount/remount? Thanks!
Replies
5
Boosts
0
Views
101
Activity
4d
Bookmarks and network remounting
In my sandboxed app, if a bookmarked network source is unavailable, is resolving the source/root security-scoped bookmark the recommended way to way to trigger a remount of the network volume? Thanks!
Replies
2
Boosts
0
Views
70
Activity
4d
URLSession on watchOS never fails over to watch's own Wi-Fi when paired iPhone has Bluetooth but no internet (-1200)
We develop a healthcare emergency-alerting app with a native watchOS companion app. We've hit a network routing issue on watchOS that we cannot work around with any public API, and it breaks a safety-critical flow (triggering an emergency alarm from the watch). Environment watchOS 26.5 on Apple Watch SE3, paired with iPhone SE 2nd Gen on iOS 26.5 Watch app deployment target: watchOS 9.0 Plain URLSession (async/await), default configuration plus waitsForConnectivity = false, allowsExpensiveNetworkAccess = true, allowsConstrainedNetworkAccess = true HTTPS to our own backend (valid public TLS certificate, no pinning) Steps to reproduce Pair the watch with the iPhone. Both on the same known Wi-Fi network. On the iPhone: turn OFF Wi-Fi and cellular data. Keep Bluetooth ON. The watch remains connected to its known Wi-Fi network (or would be, if the system brought the radio up). Trigger any HTTPS request from the watch app (foreground). Expected Since the companion iPhone has no internet, the watch should satisfy the request over its own Wi-Fi. Actual The request is routed through the companion link (ipsec1, "companion preference: prefer" in the logs) and fails after the TLS handshake dies inside the tunnel: Error Domain=NSURLErrorDomain Code=-1200 "An SSL error has occurred and a secure connection to the server cannot be made." _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9816 (errSSLClosedNoNotify) The watch never fails over to its own Wi-Fi, no matter how many times we retry or how long we wait. The same request succeeds within seconds if the user disables Bluetooth on the iPhone (watch then joins Wi-Fi directly), or restores the iPhone's internet. What we already tried waitsForConnectivity = true doesn't help; a path exists (the tunnel), it just doesn't work. Fresh URLSession per retry, backoff retries still routed via the tunnel. Per TN3135 we understand low-level networking is not available to a normal app: we prototyped NWConnection with prohibitedInterfaceTypes = [.other], and indeed on device NWPathMonitor stays .unsatisfied even when the watch has working Wi-Fi, exactly as TN3135 describes. So Network framework is not an escape hatch for us, and we are not looking to abuse the audio-streaming/CallKit carve-outs. Questions Is the companion-preferred routing supposed to fail over to the watch's own Wi-Fi when the iPhone is reachable over Bluetooth but has no internet? If yes, on what timescale, and is there anything an app can do to help the system notice the dead path sooner? Is there ANY supported way for a foreground watchOS app to express "do not use the companion link for this request"? We found only the private _companionProxyPreference SPI, which we obviously can't ship. If the answer to both is "no", what is the recommended pattern for safety-critical requests in this state is failing fast and instructing the user to disable iPhone Bluetooth really the intended UX? Related earlier reports of the same behavior: https://developer.apple.com/forums/thread/759321 https://developer.apple.com/forums/thread/107964
Replies
0
Boosts
0
Views
46
Activity
4d
Which storage capacity key should be used for offline video downloads: volumeAvailableCapacityKey or volumeAvailableCapacityForImportantUsageKey?
I’m trying to understand which storage capacity key is the correct one to use when deciding whether my app can start downloading offline video content. I read the documentation here: https://developer.apple.com/documentation/foundation/checking-volume-storage-capacity but I still don’t fully understand the intended usage difference between: volumeAvailableCapacityKey volumeAvailableCapacityForImportantUsageKey My app allows users to download videos for offline viewing. These downloads may remain on the device for a long time (days or even months), so they are not just temporary cache files. On one hand, this seems to match the description of “storing data based on a user request”, which suggests using volumeAvailableCapacityForImportantUsageKey. On the other hand, my understanding is that this value may assume the system is willing to aggressively purge caches and reclaim space for this “important usage”. I’m worried this could lead to unexpected or unpleasant side effects for the user if my app relies on that space. What confuses me even more is that the values are significantly different on my device: iPhone Settings reports about 142 GB free volumeAvailableCapacityKey returns only ~56 GB volumeAvailableCapacityForImportantUsageKey returns ~132 GB So my question is: For an app that downloads videos for offline playback — where the user explicitly requested the download, but the content may stay on device for a long time — which value is the recommended one to use when deciding whether there is enough free space to start the download? Should offline media downloads generally be treated as “important usage” in the sense intended by this API?
Replies
3
Boosts
0
Views
626
Activity
3w
How to retrieve device model name via sysctl
Model Name: MacBook Air Model Identifier: Mac17,3 I know it's possible to retrive model-identifier by running the command "sysctl hw.model", but is there another key to retrieve the model-name? ("MacBook Air" instead of "Mac17,3")
Replies
2
Boosts
0
Views
238
Activity
3w
-startDownloadingUbiquitousItemAtURL:error: and NSURLUbiquitousItemDownloadRequestedKey
I'm trying to update the iCloud data handling in our app, and I'm running into an issue with a particular file on one particular device. This file never downloads & I haven't been able to pinpoint what's off about it. Right now we just have 2 iCloud accounts & a handful of devices, so I haven't been able to narrow it down yet, but in most cases, all the cloud files download as expected. However, whether or not the file eventually downloads, the NSURLUbiquitousItemDownloadRequestedKey key seems to be completely useless. For the following code: NSError *error = nil; BOOL success = [[NSFileManager defaultManager] startDownloadingUbiquitousItemAtURL:self.fileURL error:&error]; if (!success) { NSLog(@"error downloading %@ : %@", self.fileURL, error); } else { NSDictionary *resourceValues = [self.fileURL resourceValuesForKeys:@[NSURLUbiquitousItemDownloadRequestedKey, NSURLUbiquitousItemIsDownloadingKey, NSURLUbiquitousItemDownloadingErrorKey, NSURLUbiquitousItemDownloadingStatusKey] error:&error]; if (!error) { NSString *downloadStatus = resourceValues[NSURLUbiquitousItemDownloadingStatusKey]; bool downloadRequested = [resourceValues[NSURLUbiquitousItemDownloadRequestedKey] boolValue]; NSLog(@"download requested: %d", downloadRequested); } // ... } downloadRequested is always false, regardless of whether or not the cloud file eventually downloads. I have 2 questions: is there a way to actually check if a download has been requested for a file? what could be preventing this file from downloading? -startDownloadingUbiquitousItemAtURL:error: doesn't report an error, NSURLUbiquitousItemDownloadingErrorKey is always nil, and no error is reported in the NSMetadataQuery observer.
Replies
4
Boosts
0
Views
482
Activity
3w
concurrent downloading of files with URLSession downloadTask with background configuration.
According to documentation, the URLSession background tasks continue even when the app is suspended. What is the lifespan of the URLSessionDownloadDelegate object when app is suspended or terminated? Will it get re-created and re-initialize properties when the app re-launches, or will it somehow restore the existing property values? Also, urlSessionDidFinishEvents not getting called, and what do we need to do there with the backgroundCompletionHandler? Any insights are much appreciated. We are getting ready to launch and this is a roadblock. (visionOS26.4) Thank you. @Observable class DownloadManager: NSObject, URLSessionDownloadDelegate { ... let config = URLSessionConfiguration.background(withIdentifier: "TestDL") config.sessionSendsLaunchEvents = true var urlSession = URLSession(configuration: config, delegate: self, delegateQueue: nil) func downloadFiles(... { // initiate multiple file downloads concurrently for url in urlList { let task = urlSession.downloadTask(with: url) task.resume() } } func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { ... func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { ... func urlSession(_: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { ... // Not getting called ?? // Is this only called when app is suspended/terminated? func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) { print("didFinishEvents") Task { @MainActor in //urlSession?.finishTasksAndInvalidate() //urlSession = nil // not sure what to do here: if let appDelegate = UIApplication.shared.delegate as? AppDelegate, let completionHandler = appDelegate.backgroundCompletionHandler { completionHandler() appDelegate.backgroundCompletionHandler = nil } } }
Replies
5
Boosts
0
Views
729
Activity
May ’26
[iOS 26.x] WKWebView crashes with NSInternalInconsistencyException — KVO inconsistency on configuration.enforcesChildRestrictions from STScreenTimeConfigurationObserver
Summary We are seeing a recurring fatal NSInternalInconsistencyException on iOS 26.x devices. The crash originates entirely from system frameworks (Foundation / WebKit / Screen Time / NSXPCConnection) — there are no app frames in the stack. The exception is raised from an XPC reply on a worker thread, so the host app cannot wrap it in @try/@catch. The crash appears to be a KVO consistency check failing inside the platform's internal Screen Time observer (STScreenTimeConfigurationObserver) when it observes WKWebView's configuration.enforcesChildRestrictions key path. The exception message states the value of the intermediate key configuration changed without an appropriate KVO notification. Environment iOS versions: 26.2.1 (also seen on 26.0.x – 26.2.x) Devices: iPhone 13 (iPhone14,5), iPhone 16 Plus, others App orientation: portrait Process state at crash: BACKGROUND (most occurrences) App uses WKWebView in several screens (link preview, in-app web, 3rd-party SDK web views) Crash is recurring across multiple users on iOS 26.x and is reproducible at scale in production Exception Name: NSInternalInconsistencyException Reason: Cannot update for observer <WKScreenTimeConfigurationObserver 0x...> for the key path "configuration.enforcesChildRestrictions" from <STScreenTimeConfigurationObserver 0x...>, most likely because the value for the key "configuration" has changed without an appropriate KVO notification being sent. Check the KVO-compliance of the STScreenTimeConfigurationObserver class. Crashing thread (top frames) 0 CoreFoundation __exceptionPreprocess 1 libobjc.A.dylib objc_exception_throw 2 Foundation -[NSKeyValueNestedProperty object:withObservance:didChangeValueForKeyOrKeys:recurse:forwardingValues:] 3 Foundation NSKeyValueDidChange 4 Foundation -[NSObject(NSKeyValueObservingPrivate) _changeValueForKeys:count:maybeOldValuesDict:maybeNewValuesDict:usingBlock:] 5 Foundation -[NSObject(NSKeyValueObservingPrivate) _changeValueForKey:key:key:usingBlock:] 6 Foundation NSSetObjectValueAndNotify 7 CoreFoundation invoking 8 Foundation -[NSInvocation invoke] 9 Foundation 10 Foundation -[NSXPCConnection _decodeAndInvokeReplyBlockWithEvent:sequence:replyInfo:] 11 Foundation __88-[NSXPCConnection _sendInvocation:orArguments:count:methodSignature:selector:withProxy:]_block_invoke_5 12 libxpc.dylib _xpc_connection_reply_callout 13 libxpc.dylib _xpc_connection_call_reply_async 14 libdispatch.dylib _dispatch_mach_msg_async_reply_invoke 15 libdispatch.dylib _dispatch_root_queue_drain_deferred_item 16 libdispatch.dylib _dispatch_kevent_worker_thread (Every frame above frame 0 lives in the system. No app frames are present.) What we observed Crash fires asynchronously on a libdispatch kevent worker thread, triggered by an XPC reply from the Screen Time service. The exception is thrown while the platform updates a chained KVO key path (configuration.enforcesChildRestrictions) on a WKWebView instance. The intermediate key configuration apparently changed without a paired willChange/didChange notification, which Foundation's KVO machinery then flags as inconsistency. Because the throw happens on the XPC reply path, there is no app-level synchronous frame we can wrap to recover. The exception unwinds straight into std::__terminate. What we tried (no effect) Confirmed all WKWebView creation and release happens on the main thread. Stop loading and nil out navigationDelegate before releasing the WKWebView. Avoided mutating WKWebViewConfiguration after the WKWebView is created. Checked for any custom KVO on WKWebView.configuration in app code — none exists. The crash still reproduces; we have no path to mitigate it from the application side. Questions for Apple / the community Is STScreenTimeConfigurationObserver expected to observe WKWebView.configuration.enforcesChildRestrictions under all conditions on iOS 26, or only when Screen Time / Communication Limits / Child Restrictions are enabled on the device? 2. Is there a public API (WKWebViewConfiguration option, Info.plist key, etc.) to opt a WKWebView out of Screen Time observation for hosts that do not need Screen Time integration for their web content? 3. Is this a known regression in iOS 26.x KVO chained-key-path notification posting inside WebKit's Screen Time integration? If so, is a fix slated for an upcoming 26.x release? 4. Is there any recommended workaround on the application side that does not rely on swizzling private Foundation / NSXPCConnection methods? Reproduction notes We do not have a deterministic local repro. Crashes are heavily concentrated on: iOS 26.2.1 Devices with Screen Time / Communication Limits / Child Restrictions configured at the OS level App entering the BACKGROUND state shortly after a WKWebView session If anyone has a reliable local repro on a developer device, please share — we would also like to file a Feedback Assistant report with steps. Filed Feedback Will attach FB number once filed. Thanks in advance.
Replies
1
Boosts
0
Views
948
Activity
May ’26
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
619
Activity
May ’26
NSURLSession background downloadTasks sometimes calling urlSession(_:downloadTask:didFinishDownloadingTo:) *twice*
I've just implemented background session downloads, and in testing (with 1044 downloadTasks), I'm seeing some strange behavior that's not 100% reproducible. Sometimes when I background the app, when I foreground it (or the OS does), the URLSessionDownloadDelegate's function urlSession(_:downloadTask:didFinishDownloadingTo:) gets called twice. I'm also logging the URLSessionTaskDelegate's function urlSession(_:task:didCompleteWithError:) and in this case, it does not get called between calls to didFinishDownloadingTo. Both cases are being called with the exactly same task, session and location. The first call copies the location to a semi-permanent destination (and I confirmed that file is correct), and the second call fails on move because the destination already exists. I can obviously work around this fairly easily, but wondering if I'm missing something or if there's a bug. It does appear to happen more reliably when I background for 15 seconds or longer. A second issue which is reproducible is that while backgrounded, some files are completing downloads and never calling the download delegate's urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:) I tried resuming one or all of the tasks in applicationDidBecomeActive as suggested in multiple other forums posts, but neither of those seems to resolve the issue. Again, I can work around this (using a combination of totalBytesWritten and the known size of files which have completed downloads), but I'm wondering if I'm missing something obvious. I actually thought that perhaps the resume() workaround was causing the first issue, but removing it does not have an effect.
Replies
8
Boosts
0
Views
2.1k
Activity
May ’26