iCloud & Data

RSS for tag

Learn how to integrate your app with iCloud and data frameworks for effective data storage

CloudKit Documentation

Posts under iCloud & Data subtopic

Post

Replies

Boosts

Views

Activity

How to handle required @relationship optionals in SwiftData CloudKit?
Hi all, As you know, when using SwiftData Cloudkit, all relationships are required to be optional. In my app, which is a list app, I have a model class Project that contains an array of Subproject model objects. A Subproject also contains an array of another type of model class and this chain goes on and on. In this type of pattern, it becomes really taxxing to handle the optionals the correct way, i.e. unwrap them as late as possible and display an error to the user if unable to. It seems like most developers don't even bother, they just wrap the array in a computed property that returns an empty array if nil. I'm just wondering what is the recommended way by Apple to handle these optionals. I'm not really familiar with how the CloudKit backend works, but if you have a simple list app that only saves to the users private iCloud, can I just handwave the optionals like so many do? Is it only big data apps that need to worry? Or should we always strive to handle them the correct way? If that's the case, why does it seem like most people skip over them? Be great if an Apple engineer could weigh in.
3
0
134
Oct ’25
UIImage causes memory to run out
I have a project that currently has data saved locally and I'm trying to get it to sync over multiple devices. Currently basic data is syncing perfectly fine, but I'm having issues getting the images to convert to data. From what I've researched it because I'm using a UIImage to convert and this caches the image It works fine when there's only a few images, but if there's several its a pain The associated code func updateLocalImages() { autoreleasepool { let fetchRequest: NSFetchRequest<Project> = Project.fetchRequest() fetchRequest.predicate = NSPredicate(format: "converted = %d", false) fetchRequest.sortDescriptors = [NSSortDescriptor(keyPath: \Project.statusOrder?.sortOrder, ascending: true), NSSortDescriptor(keyPath: \Project.name, ascending: true)] do { let projects = try viewContext.fetch(fetchRequest) for project in projects { currentPicNumber = 0 currentProjectName = project.name ?? "Error loading project" if let pictures = project.pictures { projectPicNumber = pictures.count for pic in pictures { currentPicNumber = currentPicNumber + 1 let picture : Picture = pic as! Picture if let imgData = convertImage(picture: picture) { picture.pictureData = imgData } } project.converted = true saveContext() } } } catch { print("Fetch Failed") } } } func convertImage(picture : Picture)-> Data? { let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) let path = paths[0] if let picName = picture.pictureName { let imagePath = path.appendingPathComponent(picName) if let uiImage = UIImage(contentsOfFile: imagePath.path) { if let imageData = uiImage.jpegData(compressionQuality: 0.5) { return imageData } } } return nil }```
3
0
992
Jan ’25
SwiftData: Crash when deleting from model, but only in prod
I'm testing my app before releasing to testers, and my app (both macOS and iOS) is crashing when I perform one operation, but only in the production build. I have data that loads from a remote source, and can be periodically updated. There is an option to delete all of that data from the iCloud data store, unless the user has modified a record. Each table has a flag to indicate that (userEdited). Here's the function that is crashing: func deleteCommonData<T:PersistentModel & SDBuddyModel>(_ type: T.Type) throws { try modelContext.delete(model: T.self, where: #Predicate<T> { !$0.userEdited }) } Here's one of the calls that results in a crash: try modelManager.deleteCommonData(Link.self) Here's the error from iOS Console: SwiftData/DataUtilities.swift:85: Fatal error: Couldn't find \Link.<computed 0x0000000104b9d208 (Bool)> on Link with fields [SwiftData.Schema.PropertyMetadata(name: "id", keypath: \Link.<computed 0x0000000104b09b44 (String)>, defaultValue: Optional("54EC6602-CA7C-4EC7-AC06-16E7F2E22DE7"), metadata: nil), SwiftData.Schema.PropertyMetadata(name: "name", keypath: \Link.<computed 0x0000000104b09b84 (String)>, defaultValue: Optional(""), metadata: nil), SwiftData.Schema.PropertyMetadata(name: "url", keypath: \Link.<computed 0x0000000104b09bc4 (String)>, defaultValue: Optional(""), metadata: nil), SwiftData.Schema.PropertyMetadata(name: "desc", keypath: \Link.<computed 0x0000000104b09c04 (String)>, defaultValue: Optional(""), metadata: nil), SwiftData.Schema.PropertyMetadata(name: "userEdited", keypath: \Link.<computed 0x0000000104b09664 (Bool)>, defaultValue: Optional(false), metadata: nil), SwiftData.Schema.PropertyMetadata(name: "modified", keypath: \Link.<computed 0x0000000104b09c44 (Date)>, defaultVal<…> Here's a fragment of the crash log: Exception Type: EXC_BREAKPOINT (SIGTRAP) Exception Codes: 0x0000000000000001, 0x000000019373222c Termination Reason: Namespace SIGNAL, Code 5, Trace/BPT trap: 5 Terminating Process: exc handler [80543] Thread 0 Crashed: 0 libswiftCore.dylib 0x19373222c _assertionFailure(_:_:file:line:flags:) + 176 1 SwiftData 0x22a222160 0x22a1ad000 + 479584 2 SwiftData 0x22a2709c0 0x22a1ad000 + 801216 3 SwiftData 0x22a221b08 0x22a1ad000 + 477960 4 SwiftData 0x22a27b0ec 0x22a1ad000 + 844012 5 SwiftData 0x22a27b084 0x22a1ad000 + 843908 6 SwiftData 0x22a28182c 0x22a1ad000 + 870444 7 SwiftData 0x22a2809e8 0x22a1ad000 + 866792 8 SwiftData 0x22a285204 0x22a1ad000 + 885252 9 SwiftData 0x22a281c7c 0x22a1ad000 + 871548 10 SwiftData 0x22a27cf6c 0x22a1ad000 + 851820 11 SwiftData 0x22a27cc48 0x22a1ad000 + 851016 12 SwiftData 0x22a27a6b0 0x22a1ad000 + 841392 13 SwiftData 0x22a285b2c 0x22a1ad000 + 887596 14 SwiftData 0x22a285a10 0x22a1ad000 + 887312 15 SwiftData 0x22a285bcc 0x22a1ad000 + 887756 16 SwiftData 0x22a27cf6c 0x22a1ad000 + 851820 17 SwiftData 0x22a27cc48 0x22a1ad000 + 851016 18 SwiftData 0x22a27a6b0 0x22a1ad000 + 841392 19 SwiftData 0x22a27c0d8 0x22a1ad000 + 848088 20 SwiftData 0x22a27a654 0x22a1ad000 + 841300 21 SwiftData 0x22a1be548 0x22a1ad000 + 70984 22 SwiftData 0x22a1cfd64 0x22a1ad000 + 142692 23 SwiftData 0x22a1b9618 0x22a1ad000 + 50712 24 SwiftData 0x22a1d2e8c 0x22a1ad000 + 155276 25 CoreData 0x187fbb568 thunk for @callee_guaranteed () -> (@out A, @error @owned Error) + 28 26 CoreData 0x187fc2300 partial apply for thunk for @callee_guaranteed () -> (@out A, @error @owned Error) + 24 27 CoreData 0x187fc19c4 closure #1 in closure #1 in NSManagedObjectContext._rethrowsHelper_performAndWait<A>(fn:execute:rescue:) + 192 28 CoreData 0x187fbbda8 thunk for @callee_guaranteed @Sendable () -> () + 28 29 CoreData 0x187fbbdd0 thunk for @escaping @callee_guaranteed @Sendable () -> () + 28 30 CoreData 0x187f663fc developerSubmittedBlockToNSManagedObjectContextPerform + 252 31 libdispatch.dylib 0x180336ac4 _dispatch_client_callout + 16 32 libdispatch.dylib 0x18032c940 _dispatch_lane_barrier_sync_invoke_and_complete + 56 33 CoreData 0x187fd7290 -[NSManagedObjectContext performBlockAndWait:] + 364 34 CoreData 0x187fc1fb8 NSManagedObjectContext.performAndWait<A>(_:) + 544 35 SwiftData 0x22a1b877c 0x22a1ad000 + 46972 36 SwiftData 0x22a1be2a8 0x22a1ad000 + 70312 37 SwiftData 0x22a1c0e34 0x22a1ad000 + 81460 38 SwiftData 0x22a23ea94 0x22a1ad000 + 596628 39 SwiftData 0x22a256828 0x22a1ad000 + 694312 40 Sourdough Buddy 0x104e5dc98 specialized ModelManager.deleteCommonData<A>(_:) + 144 (ModelManager.swift:128) [inlined] 41 Sourdough Buddy 0x104e5dc98 closure #1 in SettingsView.clearStarterData.getter + 876 (SettingsView.swift:243) It works if I do the following instead: try modelContext.delete(model: Link.self, where: #Predicate { !$0.userEdited }) Why would the func call work in development, but crash in production? And why does doing the more verbose way work instead? I think this is a bug. Thanks
3
0
68
6d
Accessing "iCloud Drive" folder in Files on iPhone from App written in Swift
I am trying to read and write a text file from an App written in Swift in XCode directly to the "iCloud Drive" folder in Files on the iPhone. The app worked readlly reading and writing to the Documents folder in the App container, and then readily to the "On My iPhone" folder in Files after adding 2 lines to the plist that I found in a search online. But I have been unable to get to the iCloud Drive folder. I found an item called "Enabling Document Storage in iCloud Drive" in "iCloud Design Guide" with additional plist entries that states "These settings allow iCloud Drive to provide public access to the files stored in your app’s container": NSUbiquitousContainers iCloud.com.example.MyApp NSUbiquitousContainerIsDocumentScopePublic NSUbiquitousContainerSupportedFolderLevels Any NSUbiquitousContainerName MyApp I think I changed the MyApp items appropriately. I have enabled iCloud in my App and the XCode General, and Signing entries. But this does not work. There are no error messages and no "Steps" shown in the "Capabilities" entry in Xcode. A little help? :-)
3
0
1.1k
Jan ’25
NSFileVersion.currentVersionOfItem not consistent across devices after simultaneous edit
I’m building an app that edits files in iCloud and uses an NSFilePresenter to monitor changes. When a conflict occurs, the system calls presentedItemDidGain(_:). In that method, I merge the versions by reading the current (canonical) version using NSFileVersion.currentVersionOfItem(at:) and the conflicting ones using NSFileVersion.unresolvedConflictVersionsOfItem(at:). This generally works, but sometimes, if two devices edit the same file at the same time, each device sees its own local version as the current one. For example: Device A writes fileVerA (slightly later in real time) Device B writes fileVerB On Device A all works fine, currentVersionOfItem returns fileVerA, as expected, and unresolvedConflictVersionsOfItem returns [fileVerB]. But on Device B, currentVersionOfItem returns fileVerB!? And unresolvedConflictVersionsOfItem returns the same, local file [fileVerB], without any hint of the other conflicting version, fileVerA. Later, the newer version from the Device A arrives on Device B as a normal, non-conflicting update via presentedItemDidChange(_:). This seems to contradict Apple’s documentation: “The currentVersionOfItemAtURL: method returns an NSFileVersion object representing what’s referred to as the current file; the current file is chosen by iCloud on some basis as the current “conflict winner” and is the same across all devices.” Is this expected behavior, or a bug in how iCloud reports file versions?
3
0
152
2w
Custom NSMigrationPolicy methods not invoked when NSMappingModel is created in code
Hi, I’m running into an issue with Core Data migrations using a custom NSMappingModel created entirely in Swift (not using .xcmappingmodel files). Setup: • I’m performing a migration with a manually constructed NSMappingModel • One of the NSEntityMapping instances is configured as follows: • mappingType = .customEntityMappingType (or .transformEntityMappingType) • entityMigrationPolicyClassName is set to a valid subclass of NSEntityMigrationPolicy • The class implements the expected methods like: @objc func createDestinationInstances(…) throws { … } @objc func createCustomDestinationInstance(…) throws -> NSManagedObject { … } The policy class is instantiated (confirmed via logging in init()), but none of the migration methods are ever called. I have also tried adding valid NSPropertyMapping instances with real valueExpression bindings to force activation, but that didn’t make a difference. Constraints: • I cannot use .xcmappingmodel files in this context due to transformable attributes not compatible with the visual editor. • Therefore, I need the entire mapping model to be defined in Swift. Workaround: As a temporary workaround, I’m migrating the data manually using two persistent stores and NSManagedObjectContext, but I’d prefer to rely on NSMigrationManager as designed. Question: Is there a known limitation that prevents Core Data from invoking NSMigrationPolicy methods when using in-memory NSMappingModel instances? Or is there any specific setup required to trigger them when not loading from .xcmappingmodel? Thanks in advance.
3
0
108
Oct ’25
can't reach CloudKit dashboard
Hello there, I have a problem reaching the CloudKit dashboard. Every time I login, the login successes but then I get the error: An error has caused this web page to stop working correctly. This also happens when I click on the Button CloudKit dashboard. Then I can reload the page, but the same errors occurs again and again. Can someone help me with this problem? Thank you very much
3
4
142
May ’25
SwiftData: Unexpected backing data for snapshot creation
When deleting a SwiftData entity, I sometimes encounter the following error in a document based SwiftUI app: Fatal error: Unexpected backing data for snapshot creation: SwiftData._FullFutureBackingData<MyEntityClass> The deletion happens in a SwiftUI View and the code used to retrieve the entity is standard (the ModelContext is injected from the @Environment): let myEntity = modelContext.model(for: entityIdToDelete) modelContext.delete(myEntity) Unfortunately, I haven't yet managed to isolate this any further in order to come up with a reproducible PoC. Could you give me further information about what this error means?
3
0
179
2w
What is going on with transformable
Hi, I keep trying to use transformable to store an array of strings with SwiftData, and I can see that it is activating the transformer, but it keeps saying that I am still using NSArray instead of NSData. *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unacceptable type of value for attribute: property = "category"; desired type = NSData; given type = Swift.__SwiftDeferredNSArray; value = ( yo, gurt ).' terminating due to uncaught exception of type NSException CoreSimulator 1010.10 - Device: iPhone 16 18.0 (6879535B-3174-4025-AD37-ED06E60291AD) - Runtime: iOS 18.0 (22A3351) - DeviceType: iPhone 16 Message from debugger: killed @Model class MyModel: Identifiable, Equatable { @Attribute(.transformable(by: StringArrayTransformer.self)) var category: [String]? @Attribute(.transformable(by: StringArrayTransformer.self)) var amenities: [String]? var image: String? var parentChunck: HenricoPostDataChunk_V1? init(category: [String]?, amenities: [String]?) { self.category = category self.amenities = amenities } } class StringArrayTransformer: ValueTransformer { override func transformedValue(_ value: Any?) -> Any? { print(value) guard let array = value as? [String] else { return nil } let data = try? JSONSerialization.data(withJSONObject: array, options: []) print(data) return data } override func reverseTransformedValue(_ value: Any?) -> Any? { guard let data = value as? Data else { return nil } let string = (try? JSONSerialization.jsonObject(with: data, options: [])) as? [String] print(string) return string } override class func transformedValueClass() -> AnyClass { return NSData.self } override class func allowsReverseTransformation() -> Bool { return true } static func register() { print("regitsering") ValueTransformer.setValueTransformer(StringArrayTransformer(), forName: .stringArrayTransformerName) } } extension NSValueTransformerName { static let stringArrayTransformerName = NSValueTransformerName("StringArrayTransformer") }
3
0
173
Jul ’25
SwiftData: Failed to decode a composite attribute
I changed an enum value from this: enum Kind: String, Codable, CaseIterable { case credit } to this: enum Kind: String, Codable, CaseIterable { case credit = "Credit" } And now it fails to load the data. This is inside of a SwiftData model. I get why the error is occurring, but is there a way to resolve this issue without having to revert back or delete the data? Error: dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "Cannot initialize Kind from invalid String value credit", underlyingError: nil))
3
0
800
Nov ’24
CKSyncEngine save existing CKRecord
I have transitioned to CKSyncEngine for syncing data to iCloud, and it is working quite well. I have a question regarding best practices for modifying and saving a CKRecord which already exists in the private or shared database. In my current app, most CKRecords will never be modified after saving to the database, so I do not persist a received record locally after updating my local data model. In the rare event that the local data for that record is modified, I manually fetch the associated server record from the database, modify it, and then use CKSyncEngine to save the modified record. As an alternative method, I can create a new CKRecord locally with the corresponding recordID and the modified data, and then use CKSyncEngine to attempt to save that record to the database. Doing so generates an error in the delegate method handleSentRecordZoneChanges, where I receive the local record I tried to save back inevent.failedRecordSaves with a .serverRecordChanged error, along with the corresponding server CKRecord. I can then update that server record with the local data and re-save using CKSyncEngine. I have not yet seen any issues when doing it this way. The advantage of the latter method is that CKSyncEngine handles the entire database operation, eliminating the manual fetch step. My question is: is this an acceptable practice, or could this result in other unforeseen issues?
2
0
79
Apr ’25
Share an object managed by NSPersistentCloudKitContainer with other users
One question I often see on DevForums and in my day DTS job is if a Core Data object managed by NSPersistentCloudKitContainer can be shared with other iCloud users. The answer is yes but you need to do it using CloudKit API directly because NSPersistentCloudKitContainer doesn’t support CloudKit shared database (CKContainer.sharedCloudDatabase) today. Assuming you have a Core Data object, let’s say a document, that you’d like to collaborate with your colleagues: You are the document owner and can use NSPersistentCloudKitContainer to fully manages the document and synchronize it across your devices. You can grab a CloudKit record associated with your document from NSPersistentCloudKitContainer using record(for:) or recordID(for:), and share it to your colleagues using UICloudSharingController. See our Sharing CloudKit Data with Other iCloud Users - https://developer.apple.com/documentation/cloudkit/sharing_cloudkit_data_with_other_icloud_users sample for how to share a CloudKit record. After accepting the sharing, your colleague, as a participant, can view or edit the shared document. The document resides in the participant’s CloudKit shared database and you have to manage it with your own code. When your colleague edits and saves the shared document, the changes go to the owner’s private database, and eventually synchronize to NSPersistentCloudKitContainer on the owner side.  As you can see, you need to implement #2 and #3 with your own code because NSPersistentCloudKitContainer can’t manage the data in the participant's shared database. If you have any difficulty after going through the above sample code, you can contact Apple’s DTS for help.
2
0
936
Feb ’25
How to change from non-versioned to versioned schema in swiftdata?
My app is using SwiftData, but I deployed it to the app store with no VersionedSchema applied without thinking about migrating the model. Now I need to migrate the data and I need help from someone who has experience moving from non-versioned to versioned. Assuming I currently have a version1, version2 schema, it works fine for the initial install situation, but when I migrate to version1, version2 in an app that is listed on the app store, I run into problems. I don't have any logs to show for it. Thread 1: EXC_BAD_ACCESS (code=2, address=0x16a6578f0) If anyone has had the same experience as above, please respond, thanks! Let me know what kind of logs you need and I'll add them as a comment.
2
1
967
Nov ’24
How to import large data from Server and save it to Swift Data
Here’s the situation: • You’re downloading a huge list of data from iCloud. • You’re saving it one by one (sequentially) into SwiftData. • You don’t want the SwiftUI view to refresh until all the data is imported. • After all the import is finished, SwiftUI should show the new data. The Problem If you insert into the same ModelContext that SwiftUI’s @Environment(.modelContext) is watching, each insert may cause SwiftUI to start reloading immediately. That will make the UI feel slow, and glitchy, because SwiftUI will keep trying to re-render while you’re still importing. How to achieve this in Swift Data ?
2
0
104
Apr ’25
Fetching strategies - Do not fetch redundant data. ETags, Lastmodified, own API? Recommendations, practice?
I am developing an Xcode app with a job feed, with profile view, with chat eg. I fetch using federatet queries to my microservices thru Apollo Router. Infront of the Apollo Router i Have a Kong that adds a X user ID, that the microservices use for personalized feed and other user info. The info is stored with SwiftData. My thought is that i should add a better way of controlling when i need to fetch. I have a “lastupdateAPI” with different entities (profile, profile picture eg). So when nothing has changed we do not fetch. But rather then using a own API for this, isnt ETag better? Or is it any other recommendations with Xcode Swiftui. Good strategies for not fetching what i already have?
2
0
729
Feb ’25
CoreData CloudKit Sync not working between iOs and MacOS
Hi All, I work on a cross platform app, iOS/macOS. All devises on iOS could synchronize data from Coredata : I create a client, I see him an all iOS devices. But when I test on macOs (with TestFlight) the Mac app could not get any information from iOs devices. On Mac, cloud drive is working because I could download and upload documents and share it between all devices, so the account is working but with my App on MacOS, there is no synchronisation. idea????
2
0
1.2k
Sep ’25
joblinkapp's registerview problem
我正在使用 Core Data 开发一个 SwiftUI 项目。我的数据模型中有一个名为 AppleUser 的实体,具有以下属性:id (UUID)、name (String)、email (String)、password (String) 和 createdAt (Date)。所有属性都是非可选的。 我使用 Xcode 的自动生成创建了相应的 Core Data 类文件(AppleUser+CoreDataClass.swift 和 AppleUser+CoreDataProperties.swift)。我还有一个 PersistenceController,它使用模型名称 JobLinkModel 初始化 NSPersistentContainer。 当我尝试使用以下方法保存新的 AppleUser 对象时: 让用户 = AppleUser(上下文:viewContext) user.id = UUID() user.name = “用户 1” user.email = “...” user.password = “密码 1” user.createdAt = Date()【电子邮件格式正确,但已替换为“...”出于隐私原因】 尝试?viewContext.save() 我在控制台中收到以下错误:核心数据保存失败:Foundation._GenericObjCError.nilError, [:] 用户快照: [“id”: ..., “name”: “User1”, “email”: “...”, “password”: “...”, “createdAt”: ...] 所有字段都有有效值,核心数据模型似乎正确。我还尝试过: • 检查 NSPersistentContainer(name:) 中的模型名称是否与 .xcdatamodeld 文件 (JobLinkModel) 匹配 • 确保正确设置 AppleUser 实体类、模块和 Codegen(类定义、当前产品模块) • 删除重复或旧的 AppleUser 类文件 • 清理 Xcode 构建文件夹并从模拟器中删除应用程序 • 对上下文使用 @Environment(.managedObjectContext) 尽管如此,在保存新的 AppleUser 对象时,我仍然会收到 _GenericObjCError.nilError。 我想了解: 为什么即使所有字段都不是零且正确分配,核心数据也无法保存? 这可能是由于一些残留的旧类文件引起的,还是我缺少设置中的其他内容? 我应该采取哪些步骤来确保 Core Data 正确识别 AppleUser 实体并允许保存? 任何帮助或指导将不胜感激。
2
0
88
Sep ’25