I'm studying sharing through this link. I followed the first steps by changing the bundle identifier of the project, the tests and placing my own container in the config and in the info.plist.
https://github.com/apple/sample-cloudkit-zonesharing
The app appears and in the log it appears that it has managed to access my iCloud, but when I click on share and share something, the following message appears in the console, on the simulator and on the iPhone:
"No options were found, providing default value for access type"
"No options were found, providing default values for permissions"
"connection invalidated"
And finally, when I click on the shared link, the following message appears:
"Item unavailable
The owner stopped sharing, or you don't have permission to open it."
iCloud & Data
RSS for tagLearn how to integrate your app with iCloud and data frameworks for effective data storage
Post
Replies
Boosts
Views
Activity
When using Core Data I would override willSave on NSManagedObject to compute alastModified value on a model object. This allowed one simple method to check changed values and set a date if necessary.
It is possible set lastModified in SwiftData, but the approaches I have found all have drawbacks when compared to the previous approach.
Hide saved model properties behind transient versions
private var textSaved: String = ""
var text: String {
get { textSaved }
set {
textSaved = newValue
lastModified = .now
}
}
I could hide every property that should update the lastModified behind a computed value, but this requires additional code for each new property and obfuscates the model definition.
Update all properties through an update function
func update<T>(keyPath: ReferenceWritableKeyPath<Player, T>, to value: T)
Paul Hudson notes a workaround where any changes are made to the model through an update function that takes a keyPath. This will add complexity to every view that wants to modify model properties, and also leaves those properties open to change through other approaches.
Use ModelContext.willSave
ModelContext sends a notification when it is about to save. This could be caught in .onReceive in a view or perhaps in some model-holding singleton, then ALL changes queried and dealt with accordingly. Perhaps the best approach here would to add willSave to all model objects so code external to the model isn't doing the lastModified logic.
This last solution feels like the best way forward that I know (ideally avoiding any .onReceive code in views). Should I prefer another solution or are there better ones I have missed?
Juust before I initiate an App Transfer...
We have sandboxed 'mobile' versions of our app (iOS and mac App) to transfer to the surviving company.
However, we also have a 'full' non-sandboxed legacy desktop dmg version of the app, available for Mac (and Win). This has access to the same iCloud folder
So the question is, what happens to the iCloud app folder on the Mac if they are only using this desktop version, once the transfer takes place? Will it remain visible on the Mac, and will it remain accessible by the desktop version if so?
I expect that although the iCloud entitlement is transferred, as it is another Team ID, the legacy app will not be able to read/write without user prompted permission. What I hope at the least, is that the folder doesn't become invisible on that machine...
I am encountering an issue with the UndoManager functionality in a SwiftUI application that integrates SwiftData for persistence. This issue occurs specifically in macOS 14 (Sonoma) but works as expected on macOS 15 (Sequoia).
The focused test app I have prepared for demonstration allows users to create ParentItem objects, and for each ParentItem, users can add multiple ChildItem objects. The undo functionality (via Cmd+Z) is not working as expected in Sonoma. When I try to undo a ChildItem addition, the UndoManager does not revert just the last ChildItem added, but instead removes all ChildItems that were added in that session.
Expected Behavior
On macOS 14 (Sonoma), I expect the UndoManager to undo only the most recent transaction (in this case, a single ChildItem insert), similar to how it functions on macOS 15 (Sequoia). Each ChildItem insertion should be treated as a separate undoable action.
Current Behavior
In macOS Sonoma, pressing Cmd+Z undoes the entire list of ChildItems added to a ParentItem in the current session, rather than just the most recent ChildItem. This appears to be an issue with undo grouping, but I’ve confirmed that no explicit grouping is being used.
Question
Is this an issue with UndoManager in macOS Sonoma, particularly in how it interacts with SwiftData persistence? What changes should I make to ensure that each ChildItem insert is treated as an individual undo action in macOS Sonoma, just as it works in Sequoia?
Any guidance on isolating the issue or recommended workarounds would be appreciated. I would expect that undo actions for each child addition would be treated as separate transactions, not grouped.
Steps Taken to Solve the Problem
I attempted to manually save the model context (modelContext.save()) after each ChildItem insert to ensure proper persistence.
I also verified that UndoManager was not grouping operations explicitly by calling beginUndoGrouping() or endUndoGrouping() myself.
This issue seems to be tied specifically to macOS Sonoma, as it does not occur on macOS Sequoia, where undoing behaves as expected.
Conditions
macOS 14 Sonoma: The issue occurs consistently.
macOS 15 Sequoia: The issue does not occur.
This issue appears to be independent of hardware, as I’ve tested it on multiple machines.
APIs/Features Potentially Involved
UndoManager in a SwiftUI application
SwiftData for persistence (using modelContext.save())
macOS version-specific behavior
Steps to reproduce
Clone test project (https://github.com/Maschina/SwiftDataUndoManagerExample), compile and run
Create a new ParentItem in the app (via plus toolbar button in the sidebar).
Add multiple ChildItems to the ParentItem (via plus toolbar button in the content / middle column of the navigation split view).
Press Cmd+Z to undo the last addition.
My app needs to share data files with multiple devices owned by a single user.
I also want to implement this mechanism without setting up a server.
Therefore, I want to make it read/write to local data on the user's own cloud drive (e.g. iCloud, Google Drive, One Drive, Dropbox) and read/use them as needed.
I have tried “.fileImporter” to get the URL, but the button is grayed out and cannot be opened.
Sorry for my poor English.
struct FilePathSettingView: View {
@State private var isPickerPresented: Bool = false
var fileControll = FileControll()
var body: some View {
VStack {
Text("Storage Setting")
Button(action:{
isPickerPresented = true
})
{
Text("Select place")
}
.fileImporter(
isPresented: $isPickerPresented,
allowedContentTypes: [.directory, .folder],
allowsMultipleSelection: false,
onCompletion: { result in
switch result {
case .success(let urls):
guard let url = urls.first else { return }
let accessGranted = url.startAccessingSecurityScopedResource()
defer {
if accessGranted {
url.stopAccessingSecurityScopedResource()
}
}
guard accessGranted else {
print("Failed to access security-scoped resource.")
return
}
fileControll.createDirectoryStructure(in: url)
case .failure(let error):
print("Failed to select directory: \(error.localizedDescription)")
}
}
)
}
}
}
I'm building a SwiftUI social photo-sharing app that uses CloudKit, where user profiles (including a CKAsset for profile pictures) are displayed throughout the app. To reduce redundant fetching of profiles across multiple views, I’m trying to implement a cache for the profile CKRecord into a custom model. (Important for handling the CKAsset for a user’s profile picture, ensuring it’s moved from the CloudKit fileURL staging area)
Here's my current approach:
struct UserProfileModel: Identifiable {
let id: String
let displayUsername: String
var profilePicture: UIImage? = nil
}
class UserProfileCache: ObservableObject {
static let shared = UserProfileCache()
@Published var cache: [UserProfileModel] = []
}
Is this a solid approach for caching CKRecords, or is there a more efficient way to structure this for performance and memory management?
I'd appreciate any input or advice on improving this architecture for performance, memory management, and handling profile updates.
Thanks in advance for your help!
I would like to create a private container and share a zone between two users with different iCloud accounts. All changes made by one would be notified with push notifications to the other user's db. Both could change the same information.
Exactly as it is done in this apple project.
https://developer.apple.com/documentation/cloudkit/shared_records/sharing_cloudkit_data_with_other_icloud_users
However, I have been reading this code for days and I am stuck on it, it is extremely complicated for my level.
I would really like to know if there is any simple project that uses the same idea to build this logic with swiftui.
Hello all!
I'm porting a ios15+ swiftui app to be compatible with Swift 6 and enabling strict concurrency checking gave me a warning that will be an error when switching to swift 6.
I'm initializing a persistence controller for my cloud kit container:
import CoreData
struct PersistenceController {
static let shared = PersistenceController()
let container: NSPersistentCloudKitContainer
init() {
container = NSPersistentCloudKitContainer(name: "IBreviary")
container.loadPersistentStores(completionHandler: { _, error in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
container.viewContext.automaticallyMergesChangesFromParent = true
}
}
The warning is on the merge policy:
Reference to var 'NSMergeByPropertyObjectTrumpMergePolicy' is not concurrency-safe because it involves shared mutable state; this is an error in the Swift 6 language mode
I have no idea how to make this concurrency safe, nor I found a documentation entry to help me with this.
Anyone have idea how to solve this?
Thanks in advance
V.
Hi,
We are currently planning an app transfer between two developer accounts.
We are concerned about files stored in the app's documents surviving the first update of the app released with the new developer account.
Since app files in documents are part of the app's container, is it safe to assume that if the user just updates the app after the transfer, the files in documents would still be there? It is important for us to confirm this before we execute our plans
Also, our app currently uses iCloud containers to save another set of files. Are these transferred with the app transfer or will the app lose access to these files? Are the files however accessible by users' by looking for them on their iCloud Drive?
Thank you!
I’m developing an app for inspections that allows users to develop their own template for inspections. Because of this, my data structure has become more than a little complex (see below).
This structure does allow a great deal in flexibility, through, as users can add groups, rows, and individual fields as needed. For example, users can add a header group, then a row to the header with fields for the Building Number, Unit Number, & Inspection Date.
However, I don’t have an efficient way to sort the inspections by the values in these fields. SwiftData sorting is keypath based, which won’t allow me to sort the inspections based on the values only in fields with specific labels.
As an alternative, I can query for fields with a specific label and do a compactMap to the inspection. But this doesn’t scale well when working with potentially hundreds or thousands of inspections as compactMap takes a lot longer then the query takes. It also doesn’t work well if I want to filter inspections or sort using values in multiple user defined fields.
Models below are greatly simplified to just get the point across. More than happy to provide some additional code if asked when I’m back at my laptop with the source code. (Typing this on my iPad at the moment)
@Model final class Inspection {
// init and other fields
var groups: [Group]?
}
@Model final class Group {
// init and other fields
@Relationship(inverse: \Inspection.groups)
var inspection: Inspection?
var rows: [Row]?
}
@Model final class Row {
// init and other fields
@Relationship(inverse: \Group.rows)
var group: Group?
var fields: [Field]?
}
@Model final class Field {
// init and other fields
var label: String?
var type: FieldType // enum, denoting what type of data this is storing
var stringValue: String?
var boolValue: Bool?
var dateValue: Date?
@Attribute(.externalStorage) var dataValue: Data?
@Relationship(inverse: \Row.fields)
var row: Row?
}
Hello everyone,
Xcode 16.0 SwiftData project. CloudKit. WidgetConfigurationIntent.
For some reason, I see a really weird behavior.
I have a shared ModelContainer and an interactive widget where I update the model data through an app intent.
This is my model -
@MainActor
class ItemsContainer {
static let shared = ItemsContainer()
var sharedModelContainer: ModelContainer!
init() {
self.sharedModelContainer = container()
}
func container() -> ModelContainer? {
if let sharedModelContainer {
return sharedModelContainer
}
let schema = Schema([
Session.self,
])
let modelConfiguration: ModelConfiguration
modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false, cloudKitDatabase: .automatic)
do {
let container = try ModelContainer(for: schema, configurations: [modelConfiguration])
self.sharedModelContainer = container
return container
} catch {
fatalError("Could not create ModelContainer: \(error)")
}
}
}
And this is how I get the model context across the app and the app intent -
let modelContext = ModelContext(ItemsContainer.shared.sharedModelContainer)
The problem is that somehow, when I update the model context in the app and then in the widget (I save the context after every change), the data is synced between the app and the widget, but then, the data is changed back to the previous state and kind of ignores the widget changes.
Didn't happen before iOS 18/Xcode 16.
Any idea?
Thanks a lot!
I have been investigating a crash where saving a context leads to a crash triggered internally by Core Data. Is there any information on what exception or fatal error it is? Or any hint of any kind which leads to NSManagedObjectContext.m:1475 (seems like this line calls abort or some sort of fatal error). Seems like this happens when the app is in background.
Exception Type: EXC_BREAKPOINT (SIGTRAP)
Exception Codes: 0x0000000000000001, 0x000000019266a3f8
Termination Reason: SIGNAL 5 Trace/BPT trap: 5
Terminating Process: exc handler [38173]
Triggered by Thread: 9
…
Thread 9 Crashed:
0 CoreData 0x000000019266a3f8 -[NSManagedObjectContext _thereIsNoSadnessLikeTheDeathOfOptimism] + 36 (NSManagedObjectContext.m:1475)
1 CoreData 0x00000001925c8fa0 -[NSManagedObjectContext save:] + 1844 (NSManagedObjectContext.m:1688)
2 MyApp 0x0000000102cc747c closure #1 in DatabaseContainer.write(_:completion:) (in MyApp) (DatabaseContainer.swift:233) + 7861372
3 MyApp 0x0000000102baab14 thunk for @escaping @callee_guaranteed () -> () (in MyApp) (<compiler-generated>:0) + 6695700
4 CoreData 0x000000019252dfe8 developerSubmittedBlockToNSManagedObjectContextPerform + 156 (NSManagedObjectContext.m:3985)
5 libdispatch.dylib 0x00000001922e2dd4 _dispatch_client_callout + 20 (object.m:576)
6 libdispatch.dylib 0x00000001922ea400 _dispatch_lane_serial_drain + 748 (queue.c:3900)
7 libdispatch.dylib 0x00000001922eaf30 _dispatch_lane_invoke + 380 (queue.c:3991)
8 libdispatch.dylib 0x00000001922f5cb4 _dispatch_root_queue_drain_deferred_wlh + 288 (queue.c:6998)
9 libdispatch.dylib 0x00000001922f5528 _dispatch_workloop_worker_thread + 404 (queue.c:6592)
10 libsystem_pthread.dylib 0x00000001e6e8c934 _pthread_wqthread + 288 (pthread.c:2696)
11 libsystem_pthread.dylib 0x00000001e6e890cc start_wqthread + 8 (:-1)
Consider this code
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
init() {
let schema = Schema([
...
])
let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false)
do {
sharedModelContainer = try ModelContainer(for: schema, configurations: [modelConfiguration])
} catch {
fatalError("Could not create ModelContainer: \(error)")
}
SettingsViewModel.shared = SettingsViewModel(modelContext: sharedModelContainer.mainContext)
}
I'm basically saving a copy of mainContext in a viewModel. And then later on uses that viewModel to operate on the models while using the mainActor.
Is this ok? That same container is also pass into the view using
.modelContainer(sharedModelContainer)
Can it be used in both ways like that?
I have a Live Activity with a button that updates a SwiftData model. This used to work in iOS 17, but not on iOS 18. The reason is that in iOS 17, when you run an AppIntent from a Live Activity, the perform() method would run in the main app's process, meaning it had access to the app's ModelContainer/ModelContext. However, in iOS 18, this is no longer the case, and the perform() method of an AppIntent now runs in the extension's process.
While I can still construct a new ModelContainer & ModelContext in the AppIntent's perform() method, the main app's container and context will not see these changes until the app is relaunched.
How can I make this work in iOS 18 now that an AppIntent executed from an extension runs in a different process from the main app?
I'm using NSPersistentCloudKitContainer and in the CloudKit dashboards I have added indexes for all my records modifiedTimestamp queryable, modifiedTimestamp sortable and recordName queryable.
But I'm still getting this warning message in the console.
<CKError 0x302acf0c0: "Invalid Arguments" (12/2015); server message = "Field 'recordName' is not marked queryable"; op = FF68EFF8D501AED8; uuid = 12C5C84B-EA9B-41A6-AD85-34023827E6FA; container ID = "z.y.x">
error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _importFinishedWithResult:importer:](1400): <PFCloudKitImporter: 0x30316c1c0>: Import failed with error:
<CKError 0x302acf0c0: "Invalid Arguments" (12/2015); server message = "Field 'recordName' is not marked queryable"; op = FF68EFF8D501AED8; uuid = 12C5C84B-EA9B-41A6-AD85-34023827E6FA; container ID = "z.y.x">
error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate recoverFromError:](2312): <NSCloudKitMirroringDelegate: 0x301b1cd20> - Attempting recovery from error: <CKError 0x302acf0c0: "Invalid Arguments" (12/2015); server message = "Field 'recordName' is not marked queryable"; op = FF68EFF8D501AED8; uuid = 12C5C84B-EA9B-41A6-AD85-34023827E6FA; container ID = "z.y.x">
error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _recoverFromError:withZoneIDs:forStore:inMonitor:](2622): <NSCloudKitMirroringDelegate: 0x301b1cd20> - Failed to recover from error: CKErrorDomain:12
Recovery encountered the following error: (null):0
error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate resetAfterError:andKeepContainer:](612): <NSCloudKitMirroringDelegate: 0x301b1cd20> - resetting internal state after error: <CKError 0x302acf0c0: "Invalid Arguments" (12/2015); server message = "Field 'recordName' is not marked queryable"; op = FF68EFF8D501AED8; uuid = 12C5C84B-EA9B-41A6-AD85-34023827E6FA; container ID = "z.y.x">
error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _requestAbortedNotInitialized:](2200): <NSCloudKitMirroringDelegate: 0x301b1cd20> - Never successfully initialized and cannot execute request '<NSCloudKitMirroringImportRequest: 0x300738eb0> A3F23AAC-F820-4044-B4B9-28DFAC4DE8D7' due to error: <CKError 0x302acf0c0: "Invalid Arguments" (12/2015); server message = "Field 'recordName' is not marked queryable"; op = FF68EFF8D501AED8; uuid = 12C5C84B-EA9B-41A6-AD85-34023827E6FA; container ID = "z.y.x">
I have an app that starts a Live Activity on a certain user action. This Live Activity contains a button that the user can tap, which updates a SwiftData model instance. However, when you return to the main app after tapping the button on the Live Activity, the views do not update to reflect the changes, even though the changes were written to the database.
The underlying issue here is that the ModelContainer/ModelContext used by the AppIntent (performed from the LiveActivity when the button is tapped), are different from the instances in the main app. Meaning that while the changes are written to the underlying storage, the in-memory instances of ModelContext/ModelContainer in the main app don't get the changes from the extension, so SwiftUI doesn't update either.
What is the recommended way to handle this scenario? Or is there one? :) Shared access to a SwiftData container is clearly supported through App Groups, so is there not a mechanism to ensure changes made by an extension are updated in real-time for the main app?
Otherwise, it seems I would have to go through and manually rerun queries that views depend on to make sure they are showing the most recent data. This is cumbersome and error-prone.
Perhaps I'm missing something? Any suggestions would be greatly appreciated.
I'm trying to safely perform the apparently complex task for a cloud storage API, namely "downloading files", but it seems like iCloud APIs are comically broken beyond repair:
-[NSFileCoordinator coordinateAccessWithIntents:queue:byAccessor:] calls the accessor block before all files have finished downloading.
The same API will also return success (called the block with error == nil) even if the download fails (e.g. the phone is in airplane mode). I both cases, the files requested by the intents will not exist.
-[NSFileManager startDownloadingUbiquitousItemAtURL:error:] does not have a completion block (Why?!?!)
Similarly, this API will return success even if it fails (e.g. airplane mode)
Manually checking NSURLUbiquitousItemIsDownloadingKey is broken as well, failed downloads (e.g. Airplane mode again) will retain their "Downloading" status, and NSURLUbiquitousItemDownloadingErrorKey is never updated.
How can one safely download a file from iCloud if all of the APIs are broken?
Hello everyone,
I’ve recently encountered an issue where my app is working perfectly fine, but I’m seeing an “OTHER” error in the CloudKit dashboard under errors. I’ve checked the logs and there doesn’t seem to be any obvious failure or issue affecting the app’s functionality.
The error doesn’t provide much detail, and I’m having trouble identifying the root cause since everything appears to be functioning as expected in the app. Has anyone else experienced this? Is this something that could be related to a server-side issue, or am I missing something on my end?
Any insights or advice would be greatly appreciated!
Thanks in advance!
With Core Data and SwiftUI we can use @SectionedFetchRequest. Does SwiftData support something similar to @SectionedFetchRequest?
For example, I want to create a lazy-loaded list that groups posts by their date.
@Model Post {
let title: String
let dateString: String // YYYY-MM-DD
let createdAt: Date
}
@SectionedFetchRequest(
entity: \Post.self,
sectionIdentifier: \Post.dateString,
sortDescriptors: [\Post.createdAt]
)
var postsByDate: SectionedFetchResults
ForEach(postsByDate) { section in
Section(header: Text(section.id)) {
ForEach(section) { post in
PostView(post)
}
}
}
Hey developers! I updated to Xcode 16 and iOS 18. I wanted to publish my first iOS 18 update but I keep getting a very strange error after building and launching the app: "Fatal error: This model instance was destroyed by calling ModelContext.reset and is no longer usable." (I haven't changed anything regarding swift data and I never call ModelContext.reset)
This error happens only after building. When I close the app and open it again (without running it through Xcode) the app never crashes and all the data is still there. I couldn't find much bout this error online. Is anyone experiencing the same?
I wonder if this is a bug in Xcode 16 or there is something wrong with my code. I also wonder if I can safely publish my update to App Store, since the error only happens after building. Thank you!