Post

Replies

Boosts

Views

Activity

Share extension with App Group: UserDefaults don't get persisted on iOS
I have a multiplatform app for Mac and iOS, for which I am implementing a share extension. This share extension has to share settings with the app itself on both platforms. I am currently trying to achieve this by adding all targets to the same App Group and using UserDefaults with the App Group as suiteName. The app consists of three targets: A multiplatform SwiftUI app, an iOS Share Extension, and a macOS Share Extension,. Settings get persisted correctly on Mac and on the iOS 26 simulator. However, on a real iOS 26 beta 3 device, the Share Extension is unable to load UserDefaults (loading anything with the App Group as a suite name returns nil). What could cause this behavior? The following log entries are generated from the Share Extension on the iOS device, but not on the iOS simulator: Couldn't read values in CFPrefsPlistSource<0x1030d3c80> (Domain: MY_APP_GROUP, User: kCFPreferencesAnyUser, ByHost: Yes, Container: (null), Contents Need Refresh: Yes): Using kCFPreferencesAnyUser with a container is only allowed for System Containers, detaching from cfprefsd 59638328 Plugin query method called (501) Invalidation handler invoked, clearing connection (501) personaAttributesForPersonaType for type:0 failed with error Error Domain=NSCocoaErrorDomain Code=4099 "The connection to service named com.apple.mobile.usermanagerd.xpc was invalidated from this process." UserInfo={NSDebugDescription=The connection to service named com.apple.mobile.usermanagerd.xpc was invalidated from this process.} LaunchServices: store (null) or url (null) was nil: Error Domain=NSOSStatusErrorDomain Code=-54 "process may not map database" UserInfo={_LSLine=72, _LSFunction=_LSServer_GetServerStoreForConnectionWithCompletionHandler, _LSFile=LSDReadService.mm, NSDebugDescription=process may not map database} Attempt to map database failed: permission was denied. This attempt will not be retried. Failed to initialize client context with error Error Domain=NSOSStatusErrorDomain Code=-54 "process may not map database" UserInfo={_LSLine=72, _LSFunction=_LSServer_GetServerStoreForConnectionWithCompletionHandler, _LSFile=LSDReadService.mm, NSDebugDescription=process may not map database} [C:1-3] Error received: Invalidated by remote connection.
1
0
46
1d
FileExporter's action label always says "Move"
I would like to implement an "Export" dialog using the .fileExporter() view modifier. The following code works correctly, but the FileExporter's action label always says "Move", which is inappropriate for the context. I would like to change it to say "Export", "Save", "Save as", or anything semantically correct. Button("Browse") { showingExporter = true } .buttonStyle(.borderedProminent) .fileExporter( isPresented: $showingExporter, document: document, contentType: .data, defaultFilename: suggestedFilename ?? fileUrl.pathComponents.last ?? "Untitled" ) { result in switch result { case .success(let url): print("Saved to \(url)") onSuccess() case .failure(let error): print(error.localizedDescription) onError(error) } } "document" is a custom FileDocument with a fileWrapper() method implemented like this: func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper { return FileWrapper(regularFileWithContents: data) } This was tested on iOS 26 beta 3.
Topic: UI Frameworks SubTopic: SwiftUI
0
0
70
5d
SwiftData: filtering against an array of PersistentIdentifiers
I would like to have a SwiftData predicate that filters against an array of PersistentIdentifiers. A trivial use case could filtering Posts by one or more Categories. This sounds like something that must be trivial to do. When doing the following, however: let categoryIds: [PersistentIdentifier] = categoryFilter.map { $0.id } let pred = #Predicate<Post> { if let catId = $0.category?.persistentModelID { return categoryIds.contains(catId) } else { return false } } The code compiles, but produces the following runtime exception (XCode 26 beta, iOS 26 simulator): 'NSInvalidArgumentException', reason: 'unimplemented SQL generation for predicate : (TERNARY(item != nil, item, nil) IN {}) (bad LHS)' Strangely, the same code works if the array to filter against is an array of a primitive type, e.g. String or Int. What is going wrong here and what could be a possible workaround?
3
0
72
Jun ’25
'NSInvalidArgumentException', reason: 'Duplicate version checksums across stages detected.'
I have an iOS app using SwiftData with VersionedSchema. The schema is synchronized with an CloudKit container. I previously introduced some model properties that I have now removed, as they are no longer needed. This results in the current schema version being identical to one of the previous ones (except for its version number). This results in the following exception: 'NSInvalidArgumentException', reason: 'Duplicate version checksums across stages detected.' So it looks like we cannot have a newer schema version with an identical content to an older schema version. The intuitive way would be to re-add the old (identical) schema version to the end of the "schemas" list property in the SchemaMigrationPlan, in order to signal that it is the newest one, and to add a migration stage back to it, thus: public enum MySchemaMigrationPlan: SchemaMigrationPlan { public static var schemas: [any VersionedSchema.Type] { [ SchemaV100.self, SchemaV101.self, SchemaV100.self ] } public static var stages: [MigrationStage] { [ migrateV100toV101, migrateV101toV100 ] } However, I am not sure if this is the right way to go, as previously, as I wanted to write unit tests for schema migration and rollback, I tried defining an inverse for each migration stage, so that I could trigger a migration and a rollback from a unit test, which resulted in an exception saying that it is not supported to downgrade a VersionedSchema. I must admit that I solved the original problem by introducing a dummy model property that I will later remove. What would have been the correct approach?
1
0
67
Jun ’25
Open child windows for a document in a document based SwiftData app
In a document based SwiftData app for macOS, how do you go about opening a (modal) child window connected to the ModelContainer of the currently open document? Using .sheet() does not really result in a good UX, as the appearing view lacks the standard window toolbar. Using a separate WindowGroup with an argument would achieve the desired UX. However, as WindowGroup arguments need to be Hashable and Codable, there is no way to pass a ModelContainer or a ModelContext there: WindowGroup(id: "myWindowGroup", for: MyWindowGroupArguments.self) { $args in ViewThatOpensInAWindow(args: args) } Is there any other way?
0
0
28
Apr ’25
Is it possible to use an additional local ModelContainer in a document based SwiftData app?
I have a document based SwiftData app in which I would like to implement a persistent cache. For obvious reasons, I would not like to store the contents of the cache in the documents themselves, but in my app's data directory. Is a use case, in which a document based SwiftData app uses not only the ModelContainers from the currently open files, but also a ModelContainer writing a database file in the app's documents directory (for cache, settings, etc.) supported? If yes, how can you inject two different ModelContexts, one tied to the currently open file and one tied to the local database, into a SwiftUI view?
0
0
33
Apr ’25
Proper way to use a ModelContext from a background thread in a document based app
What is the idiomatic way to use a ModelContext in a document based SwiftData app from a background thread? The relevant DocumentGroup initializers do not give us direct access to a ModelContainer, only to a ModelContext. Is it safe to take its modelContext.container and pass it around (for creating a ModelContext on it on a background thread) or to construct a ModelActor with it? Is it safe to e.g. put a ModelActor so created into the environment of the root view of the window and execute various async data operations on it in Tasks throughout the app, as long as these are dispatched from within the window whose root view's ModelContext was used for getting the ModelContainer?
1
1
642
Feb ’25
Document based SwiftData apps do not autosave
Document based SwiftData apps do not autosave changes to the ModelContext at all. This issue has been around since the first release of this SwiftData feature. In fact, the Apple WWDC sample project (https://developer.apple.com/documentation/swiftui/building-a-document-based-app-using-swiftdata) does not persist any data in its current state, unless one inserts modelContext.save() calls after every data change. I have reported this under the feedback ID FB16503154, as it seemed to me that there is no feedback report about the fundamental issue yet. Other posts related to this problem: https://forums.developer.apple.com/forums/thread/757172 https://forums.developer.apple.com/forums/thread/768906 https://developer.apple.com/forums/thread/764189
0
0
281
Feb ’25
DragGesture on parent conflicts with child's LongPressGesture
I have a use case in which there is a zoomable and pannable parent view, and a child view that needs to display a custom context menu on long press. (The reason why I need to implement a custom context menu is this: https://developer.apple.com/forums/thread/773810) It seems, however, that this setup produces a bug in SwiftUI. The problem is that the onChanged of the drag gesture is only invoked right before its onEnded, hence you cannot smoothly animate the drag: struct ContentView: View { var body: some View { ZStack { Rectangle() .foregroundStyle(.green) .frame(width: 200, height: 200) .onLongPressGesture { print("long press") } } .gesture(MagnifyGesture().onEnded { value in print("magnify end") }) .gesture(DragGesture() .onChanged { value in print("drag change") } .onEnded { value in print("drag end") }) } } Changing the DragGesture to a .highPriorityGesture() makes the drag's onChange execute at the correct time but results in the LongPressGesture only triggering when the user lifts up his/her finger (which was originally not the case). So it seems that the two gestures are in a sort of conflict with each other. Is there a workaround?
Topic: UI Frameworks SubTopic: SwiftUI
1
0
251
Feb ’25
Context menu previews are ignoring the parent's scaleEffect() modifier
If you add the .scaleEffect() modifier to a parent view inside of which there are children with contextMenu()-s, the context menu preview unfortunately keeps the original, unscaled size of the child view. This results in a very weird, glitchy user experience. Unfortunately, providing a custom preview that is scaled up also does not help, since even though it is the right size, it gets cropped to the unscaled size of the child view. Adding scaleEffect() to each child element individually (BEFORE the contextMenu() modifier!) does make the problem disappear. However, I would like to avoid this, since my use case is zooming into a complex graph with context menus on its nodes, and having to recalculate the position of each node manually seems to perform much worse than delegating that work to scaleEffect(). Tested on iOS 18.2 (device + emulator) Is there a workaround? Here is a minimal working example that demonstrates the problem: struct ContentView: View { var body: some View { VStack(spacing: 20) { Rectangle() .frame(width: 100, height: 100) .contextMenu { Button("Test") {} Button("Test") {} } Rectangle() .frame(width: 100, height: 100) .contextMenu { Button("Test") {} Button("Test") {} } } .scaleEffect(1.5) } } Screenshot (problem: The two squares are the same size. However, the long-tapped upper square got shrunk down before the context menu got displayed.)
Topic: UI Frameworks SubTopic: SwiftUI
2
0
262
Feb ’25
Embedding a NavigationSplitView inside a NavigationStack
Embedding a NavigationStack inside the detail view of a NavigationSplitView is described by the Apple documentation: https://developer.apple.com/documentation/swiftui/navigationsplitview However, I would like to do the opposite: embedding a NavigationSplitView inside a NavigationStack. I have found no hint in the documentation about why this shouldn't be possible, but it does not appear to be working consistently. There are many use cases where you might want to do this. E.g. you have an eBook reader that starts with a list of books (e.g. a Grid inside a NavigationStack), and when you open a book, you end up in a NavigationSplitView showing the chapter hierarchy in a sidebar. Here, you wouldn't want to have the list of books as a second sidebar, but would want an option to go back to the list of books at any time. The following trivial example correctly displays a NavigationSplitView on iPadOS, but results in an empty view on iOS: NavigationStack { NavigationSplitView { List { Text("Element1") Text("Element2") } } detail: { Text("Detail") } } Is there a workaround?
Topic: UI Frameworks SubTopic: SwiftUI
2
0
253
Jan ’25
Model instance invalidated, backing data could no longer be found in the store
I have been recently getting the following error seemingly randomly, when an event handler of a SwiftUI view accesses a relationship of a SwiftData model the view holds a reference to. I haven't yet found a reliable way of reproducing it: SwiftData/BackingData.swift:866: Fatal error: This model instance was invalidated because its backing data could no longer be found the store. PersistentIdentifier(id: SwiftData.PersistentIdentifier.ID(url: COREDATA_ID_URL), implementation: SwiftData.PersistentIdentifierImplementation) What could cause this error? Could you suggest me a workaround?
2
0
874
Dec ’24