Posts under App & System Services topic

Post

Replies

Boosts

Views

Created

Correct SwiftData Concurrency Logic for UI and Extensions
Hi everyone, I'm looking for the correct architectural guidance for my SwiftData implementation. In my Swift project, I have dedicated async functions for adding, editing, and deleting each of my four models. I created these functions specifically to run certain logic whenever these operations occur. Since these functions are asynchronous, I call them from the UI (e.g., from a button press) by wrapping them in a Task. I've gone through three different approaches and am now stuck. Approach 1: @MainActor Functions Initially, my functions were marked with @MainActor and worked on the main ModelContext. This worked perfectly until I added support for App Intents and Widgets, which caused the app to crash with data race errors. Approach 2: Passing ModelContext as a Parameter To solve the crashes, I decided to have each function receive a ModelContext as a parameter. My SwiftUI views passed the main context (which they get from @Environment(\.modelContext)), while the App Intents and Widgets created and passed in their own private context. However, this approach still caused the app to crash sometimes due to data race errors, especially during actions triggered from the main UI. Approach 3: Creating a New Context in Each Function I moved to a third approach where each function creates its own ModelContext to work on. This has successfully stopped all crashes. However, now the UI actions don't always react or update. For example, when an object is added, deleted, or edited, the change isn't reflected in the UI. I suspect this is because the main context (driving the UI) hasn't been updated yet, or because the async function hasn't finished its work. My Question I'm not sure what to do or what the correct logic should be. How should I structure my data operations to support the main UI, Widgets, and App Intents without causing crashes or UI update failures? Here is the relevant code using my third (and current) approach. I've shortened the helper functions for brevity. // MARK: - SwiftData Operations extension DatabaseManager { /// Creates a new assignment and saves it to the database. public func createAssignment( name: String, deadline: Date, notes: AttributedString, forCourseID courseID: UUID, /*...other params...*/ ) async throws -> AssignmentModel { do { let context = ModelContext(container) guard let course = findCourse(byID: courseID, in: context) else { throw DatabaseManagerError.itemNotFound } let newAssignment = AssignmentModel( name: name, deadline: deadline, notes: notes, course: course, /*...other properties...*/ ) context.insert(newAssignment) try context.save() // Schedule notifications and add to calendar _ = try? await scheduleReminder(for: newAssignment) newAssignment.calendarEventIDs = await CalendarManager.shared.addEventToCalendar(for: newAssignment) try context.save() await MainActor.run { WidgetCenter.shared.reloadTimelines(ofKind: "AppWidget") } return newAssignment } catch { throw DatabaseManagerError.saveFailed } } /// Finds a specific course by its ID in a given context. public func findCourse(byID id: UUID, in context: ModelContext) -> CourseModel? { let predicate = #Predicate<CourseModel> { $0.id == id } let fetchDescriptor = FetchDescriptor<CourseModel>(predicate: predicate) return try? context.fetch(fetchDescriptor).first } } // MARK: - Helper Functions (Implementations omitted for brevity) /// Schedules a local user notification for an event. func scheduleReminder(for assignment: AssignmentModel) async throws -> String { // ... Full implementation to create and schedule a UNNotificationRequest return UUID().uuidString } /// Creates a new event in the user's selected calendars. extension CalendarManager { func addEventToCalendar(for assignment: AssignmentModel) async -> [String] { // ... Full implementation to create and save an EKEvent return [UUID().uuidString] } } Thank you for your help.
4
0
115
1w
AppIntents crashes in prod
We implemented AppIntents using EnumerableEntityQuery and @Dependency and we are receiving these crash reports: AppIntents/AppDependencyManager.swift:120: Fatal error: AppDependency of type MyDependency.Type was not initialized prior to access. Dependency values can only be accessed inside of the intent perform flow and within types conforming to _SupportsAppDependencies unless the value of the dependency is manually set prior to access. I can't post the stack because of the Developer Forums sensitive language filter :( but basically it's just a call to suggestedEntities of MyEntityQuery that calls the dependency getter and then it crashes. My understanding was that when using @Dependency, the execution of the intent, or query of suggestedEntities in this case, would be delayed by the AppIntents framework until the dependency was added to the AppDependencyManager by me. At least that's what's happening in my tests. But in prod I'm having these crashes which I haven't been able to reproduce in dev yet. Does anyone know if this is a bug or how can this be fixed? As a workaround, I can avoid using @Dependency and AppDependencyManager completely and make sure that all operations are async and delay the execution myself until the dependency is set. But I'd like to know if there's a better solution. Thanks!
1
0
102
1w
iOS BLE Connection Timeout Policy: Per-Peripheral or Per-App Radio Session?
Hi Core Bluetooth team, I’m seeking official clarification on iOS system-level BLE connection management policy, specifically regarding idle timeouts. Question: When iOS disconnects a BLE peripheral with the error: "The connection has timed out unexpectedly." Is this timeout enforced: Per peripheral (each connection has its own idle timer), or Per app / per Bluetooth radio session (one idle timer for all BLE connections in the app)? In other words: Does a single GATT operation (e.g., a write or notification) on any one peripheral reset the idle timeout for all other BLE connections in the same app? Context (General, No App Code): This is about system behavior, not a bug in any specific app. Applies to foreground and bluetooth-central background mode. No state restoration involved. iOS 17–18, all modern devices. Why This Matters: If per-app, one keep-alive can protect multiple peripherals → simplifies design. If per-peripheral, each connection needs independent activity → higher power use. Reference: Core Bluetooth docs recommend “regular GATT operations” but don’t specify scope. WWDC sessions mention “shared Bluetooth radio” but not timeout granularity. Official Answer Requested: Is the BLE idle timeout per peripheral or per app/radio session in iOS? Thank you for the authoritative guidance.
0
0
40
1w
Presumably its not possible to use declared age range in an extension?
Its possible to add the Declared Age Range entitlement to extensions, in particular I'm looking at a Notification Service Extension. However the DAR requestAgeRange() API takes a view controller as a parameter. Presumably therefore its not possible for a notification service extension to obtain the age range itself directly? Yes the extension can read it from shared groups if the app reads it and set it into the group. However the scenario I'm thinking of is this: App runs and gets the age range. Sets its functionality accordingly. The server sends pushes which are intercepted by the notification service extension, the extension adjusts its functionality based upon what the app wrote to shared groups The user changes the age range setting, but the app doesn't run. The extension keeps receiving pushes but its functionality is now out of sync with the age range as its not able to obtain it directly
0
0
29
1w
Encountered issues when calling the sandbox environment interface to verify receipts during the development of the payment function
Currently, we are using the Apple V2 interface to develop the payment function. We generate a transaction ID on the mobile client and obtain the receipt. Now, when we call the Apple sandbox environment interface to verify the receipt, we always get a 404 error. The above is the request and response. The token used in it is also the original data after decoding, and there is no problem. Could you help me figure out what other possible reasons there might be?
0
0
18
1w
iOS 26: Maps share sheet no longer provides com.apple.mapkit.map-item and only shares short maps.apple/p/... URLs (how to get coordinates?)
Since iOS 26, the Apple Maps share sheet no longer provides a com.apple.mapkit.map-item attachment when sharing a location to my Share Extension. Additionally, on real devices the shared URL is now a short link (https://maps.apple/p/...), which does not contain coordinates. On the simulator, the URL still includes coordinates (as in previous iOS versions). I'm trying to find the official or recommended way to extract coordinates from these new short URLs. Environment: Devices: iPhone (real device) on iOS 26.0 / 26.0.1 Simulator: iOS 26.0 / 26.0.1 simulator (behaves like iOS 18 — see below) App: Share Extension invoked from Apple Maps -> Share -> my app Xcode: 26.0.1 Steps to Reproduce Open Apple Maps on iOS 26 (real device). Pick a POI (store/restaurant). Share -> choose my share extension. iOS 18 and earlier (lldb) po extensionContext?.inputItems ▿ Optional<Array<Any>> ▿ some : 1 element - 0 : <NSExtensionItem: 0x60000000c5d0> - userInfo: { NSExtensionItemAttachmentsKey = ( "<NSItemProvider: 0x600002930d20> {types = (\"public.plain-text\")}", "<NSItemProvider: 0x600002930c40> {types = (\"com.apple.mapkit.map-item\")}", "<NSItemProvider: 0x600002930bd0> {types = (\"public.url\")}" ); } Typical URL: https://maps.apple.com/place?address=Apple%20Inc.,%201%20Apple%20Park%20Way,%20Cupertino,%20CA%2095014,%20United%20States&coordinate=37.334859,-122.009040&name=Apple%20Park&place-id=I7C250D2CDCB364A&map=explore iOS 26 (lldb) po extensionContext?.inputItems ▿ 1 element - 0 : <NSExtensionItem: 0x6000000058d0> - userInfo: { NSExtensionItemAttachmentsKey = ( "<NSItemProvider: 0x600002900b60> {types = (\"public.url\")}", "<NSItemProvider: 0x600002900fc0> {types = (\"public.plain-text\")}" ); } URL looks like: https://maps.apple/p/U8rE9v8n8iVZjr On simulator iOS 26 same missing map-item provider - but the URL is still long and contains coordinates, like this: https://maps.apple.com/place?coordinate=37.334859,-122.009040&name=Apple%20Park&.. Issue The short URLs (maps.apple/p/...) cannot be resolved directly - following redirects ends with: https://maps.apple.com/unsupported The only way I've found to get coordinates is to intercept intermediate redirects - one of them contains the expanded URL with coordinate=.... Example of my current workaround: final class RedirectSniffer: NSObject, URLSessionTaskDelegate { private(set) var redirects: [URL] = [] func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest) async -> URLRequest? { if let url = request.url { redirects.append(url) } return request } } Then I look through redirects to find a URL containing "coordinate=". This works, but feels unreliable and undocumented. Questions Was the removal of com.apple.mapkit.map-item from the Maps share payload intentional in iOS 26? If yes, is there a new attachment type or API to obtain an MKMapItem? What’s the official or supported way to resolve https://maps.apple/p/... to coordinates? Is there any MapKit API or documented URL scheme for this? Is intercepting redirect chains the only option for now? Why does the iOS 26 simulator still return coordinate URLs, while real devices don't?
2
0
162
1w
Apple Pay Test cards not added to Wallet
For Apple Pay testing, I have tried the following: Sign into the Sandbox Account via Developer Settings: Settings > Developer > Sandbox Account Keep your main Apple ID for everything else Add Test Cards to Wallet: Try adding the test card numbers (MasterCard and Visa Debit, as we support only those) Apple provides in their documentation. Unfortunately, none of them are added to the wallet. All the time it gives 'Could Not Add Card'. I tried on devices with iOS 18+. Can anyone advise on this? Thanks
1
0
78
1w
For the iOS/Xcode age range validation, what is an invalidRequest error?
One of the responses to a call to AgeRangeService.shared.requestAgeRange is AgeRangeService.Error.invalidRequest. This has no documentation. What on earth is an invalid request - I mean the app just calls the API, there's no parameters supplied or anything, how can the request ever be invalid? If the app calls AgeRangeService.shared.requestAgeRange and gets this as a response then what is the app supposed to do with that?
3
0
66
1w
Live Activities Push-to-Start flows
Good morning, We are implementing Live Activities in a push-to-start flow. We wrap the listener for push to start tokens in a high priority task: if ptsListenerTask == nil || ptsListenerTask?.isCancelled == true { ptsListenerTask = Task(priority: .high) { [weak self] in for await pushToken in Activity<LiveAuctionAttributes>.pushToStartTokenUpdates { //Send token to back-end } } I've tried a few variations of this and they work well on most devices. I have seen a couple of devices that refuse to issue a push to start token. The user will have logging for the init flow and starting the PTS listener then the logs just go silent, nothing happens. One thing that seemed to work was getting the user to start a Live Activity manually (from our debugging tool) then the PTS token gets issued. This is not very reliable and working a mock live activity into the flow for obtaining a PTS token is a poor solution. Is anyone else seeing this and is there a known issue with obtaining PTS tokens? Thanks! Brad
3
1
83
1w
iPhone/iPad DFU and Apple deviceinterfaced process
Problem Description: Since Our USB hubs are capable of sending Vendor Defined Messages (VDMs) over a USB Type-C cable connection, they can programmatically place iOS, iPadOS, and macOS devices into DFU mode—without requiring any physical button interaction. Recently, we identified an issue when invoking DFU mode on an iPhone 15 using this method. Upon entering DFU mode, the device enumerates with USB Product ID 0x1881 (“Debug USB” – KIS interface). At that point, the deviceinterfaced daemon (launched by launchd) immediately detects the device and claims exclusive access to the USB interface. As a result, when our API Service attempts to communicate with the device through standard IOKit methods, it fails with the following error: 0xe00002c5 ((iokit/common) exclusive access and device already open) This prevents our libraries from reading the iBoot string (USB serial number string) that Apple devices normally expose in standard or recovery modes—information that includes ECID, CPID, CPRV, CPFM, BDID, and SCEP. This creates a significant barrier, as our API service becomes unable to perform subsequent device restoration operations as we missed the critical information. Request for Guidance: I’ve included the following context for your analysis and review. Using the launchctl unload command can temporarily stop it; however, I’d like to know if there’s an API-level mechanism to programmatically prevent deviceinterfaced from claiming access from within our API Service. Could you please advise on the following points? 1.  Managing deviceinterfaced Access • What is the proper way to stop or prevent deviceinterfaced from claiming exclusive access in this case, so that the API Service can read device information and starts restoring the device from that point? • Is there a recommended method or entitlement that allows third-party services to communicate with Apple devices while they are in Debug USB (KIS) mode? 2.  Guidelines and API Access • Are there any Apple-supported APIs or developer guidelines that would permit controlled access to the iBoot interface without conflicting with deviceinterfaced?
2
0
46
1w
How to debug SecurityAgentPlugins?
Hi, I’ve developed a custom Authorization Plugin and placed it under: /Library/Security/SecurityAgentPlugins/AuthPlugin.bundle I also updated the corresponding right in the authorization database (authorizationdb) to point to my plugin’s mechanism. However, when I invoke the right, my plugin does not get loaded. The system log shows the following errors: AuthorizationHostHelper: Init: unable to load bundle executable for plugin: AuthPlugin.bundle AuthorizationHostHelper: Processing request: Failed to create agent mechanism AuthPlugin:auth.startup.authenticate, failing authentication! Here’s what I’ve verified so far: The plugin bundle and its executable are signed and notarized successfully. The executable inside the bundle is universal (arm64 + x86_64). The bundle structure looks correct (Contents/Info.plist, Contents/MacOS/..., etc.). Despite that, the plugin fails to load at runtime. Could anyone provide advice on how to debug or trace why the SecurityAgent cannot load the bundle executable? Are there any entitlements, permissions, or SIP-related restrictions that might prevent custom authorization plugins from being loaded on modern macOS versions? Thanks in advance for any insights!
1
0
36
1w
Pairing failing after forgetting the device
Hello, I am working on iOS app acting as a central that connects to a peripheral which triggers bonding on connection. The pairing is successful on the first connection and after resetting the peripheral (and forgetting the device in Bluetooth Settings). It fails, however, after this devices is forgotten in the Bluetooth Settings at DHKey check, but the peripheral remains turned on. The peripheral is a linux device using BlueZ. This issue does not happen with Android device. Steps: Connect with the peripheral in the app using Core Bluetooth for the first time. Accept the pairing prompt. Bonding is successful and the peripheral is under MY DEVICES in Bluetooth Settings. Forget the device in Bluetooth Settings. Connect with the peripheral in the app using Core Bluetooth. Pairing prompt pops up repeatedly. Sometimes it pops up once, but the pairing is not successful as the device is not present under MY DEVICES. Connect with the peripheral in the app using Core Bluetooth another time. Pairing prompt still shows app. Restarting the peripheral fixes it and central iOS device is able to pair again. Sharing a screen shot from nRF Sniffer for SMP packets which indicate DHKey check failing. I was not able to attach whole log files because of size, let me know if needed I can share them in a different way somehow. Is there anything different in the flow between pairing for the first time and after forgetting the device?
2
0
59
1w
Why is the Apple Wallet Url Verification different between the ios18 and ios26
Basic information: The issuer has implemented the feature to active Apple Card via URL Verification. The feature implemented by issuer is supported both in the APP and Clips. When Apple queries the activation method from UnionPay, UnionPay returns the "URL" activation method to Apple. Additionally, the apple-app-site-association file has been correctly deployed, and the configuration for Universal Links has been completed. Both the APP and Clips have undergone testing for Universal Link calls. The desired experiece is that when the APP is installed, Apple Wallet launches the APP, and the user completes the activation within the APP, and if the APP is not installed, Apple Wallet calls Clips, and the user completes the activation in Clips. Problem description: Under iOS 17 and iOS 18, when triggering Apple Pay card activation, the APP or Clips can be called as expected, and the activation can be completed well. However, Under iOS 26, regardless of whether the APP is installed, under the same circumstances, an internal browser within Apple Wallet opens to access the H5 page corresponding to the URL, instead of redirecting to the APP or Clips. Please assist in confirming whether this is a new feature of iOS 26 and how the same user experience can be achieved.
1
0
30
1w
Guidance on Migrating Active Subscriptions from Apple Server Notifications v1 to v2
I’m reaching out regarding our existing in-app subscription implementation that currently uses App Store Server Notifications version 1 (v1). Our live application has a significant number of active recurring subscriptions that are being managed through the v1 webhook integration. We have now developed a revamped version of our application, which uses the same Apple Developer Account and App Store Connect setup, but in this new app version, we’ve implemented App Store Server Notifications version 2 (v2). Before moving forward with the migration, I would like to clarify the following points to ensure a smooth transition and avoid any disruptions to ongoing subscriptions: Backward Compatibility: Will existing active subscriptions (originally created and managed via v1 notifications) continue to work seamlessly once we switch to v2, or do we need to maintain both v1 and v2 endpoints during the transition? Notification Delivery: If both webhook versions are configured simultaneously, will Apple send notifications to both endpoints, or only the one currently configured in App Store Connect? Migration Strategy: What is Apple’s recommended best practice for migrating from v1 to v2 in a scenario where the live app still has active subscriptions tied to the v1 webhook? Potential Risks or Considerations: Are there any known limitations, delays, or issues that we should prepare for during this migration (for example, differences in payload structure or event types between v1 and v2 that could affect subscription lifecycle management)? I would greatly appreciate your guidance or documentation links that outline the correct migration steps and recommended approach for ensuring continuity of service for all existing subscribers.
0
0
21
1w
Question about including all project classes in ofClasses parameter when using NSKeyedUnarchiver.unarchivedObject(ofClasses:from:)
Hello, I have a question about data deserialization using NSKeyedUnarchiver in iOS SDK development. Current Situation: Previously, we were using the NSKeyedUnarchiver.unarchiveObject(with: Data) function We have changed to using the NSKeyedUnarchiver.unarchivedObject(ofClasses:from:) method to deserialize complex objects stored in UserDefaults We need to include all types in the ofClasses parameter, including Swift primitive types as well as various custom classes and structs within the project Questions: Implementation Approach: Is it correct pattern to include all classes defined in the project in the ofClasses array? Is this approach recommended? Runtime Stability: When using this approach, is there a possibility of runtime crashes? Are there any performance issues? Alternative Methods: If the current approach is not the correct pattern, what alternatives should we consider? Current Code Structure: All model classes conform to the NSSecureCoding protocol We use the requiringSecureCoding: true parameter We use a whitelist approach, explicitly listing only allowed classes I would like to know if this structure is appropriate, or if we should consider a different approach. Thank you.
4
0
107
1w
Subject: Call Directory Extension Enable Failure for Individual User
Subject: Call Directory Extension Enable Failure for Individual User Dear Apple Developer Support, We are experiencing an issue with our Call Directory Extension where one specific user cannot enable it, while thousands of other users on the same iOS version can enable it successfully. Issue Details: App: 美信 (Midea Connect) Problem: Extension fails to enable with error: "请求'美信'的数据时失败" (Failed to request data from app) Affected: 1 user out of thousands iOS Version: 26.0.1 What Works: All other users can enable the extension normally Same iOS version, no issues App Group and Extension identifier are correctly configured User Has Tried: Reinstall app - No effect Toggle extension off/on - Still fails Restart device - No improvement
0
0
32
1w
Issues Handling Multiple Incoming Calls in CallKit
Certainly! Here's a concise version of your forum post: Title: Issues Handling Multiple Incoming Calls in CallKit Body: Hello, I'm using CallKit and I am encountering challenges with handling multiple incoming calls. Current Configuration: configuration.maximumCallsPerCallGroup = 5 configuration.maximumCallGroups = 3 This setup aims to allow up to 5 calls per group. Observed Behavior: Despite the configuration, the system UI seems to limit the number of calls per group, often defaulting to "End & Accept" instead of "Hold & Accept" when a third call comes in. Questions: Is there a documented system-imposed limit on the number of calls per group or total calls, even if maximumCallGroups and maximumCallsPerCallGroup are set higher? How does the system UI behave when these limits are exceeded? Are there known UI constraints or fallback behaviors? Are there best practices for handling scenarios where the system UI cannot display all calls, such as gracefully managing incoming calls or providing alternative UI solutions? Any insights or experiences with similar configurations would be greatly appreciated. Thank you. Feel free to copy and paste this directly into the Apple Developer Forums. If you need further assistance or adjustments, let me know!
1
0
40
1w