CloudKit

RSS for tag

Store structured app and user data in iCloud containers that can be shared by all users of your app using CloudKit.

Posts under CloudKit tag

200 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

Does CloudKit guarantee CKRecord.Reference is always valid?
I'm considering using CloudKit in my app (it doesn't use Core Data) and have read as many materials as I can find. I haven't fully grasped it yet and have a basic question on CKRecord.Reference. Does CloudKit guarantee CKRecord.Reference value is always valid? By valid I mean the target CkRecord pointed by the CKRecord.Reference exists in the database. Let's consider an example. Suppose there are two tables: Account and Transaction: Account Table: AccountNumber Currency Rate ------------- -------- ---- a1 USD 0.03 Transaction Table: TransactionNumber AccountNumber Amount ----------------- ------------- ------ t1 a1 20 Now suppose user does the following: User first deletes account a1 and its associated transactions t1 on device A. The device saves the change to cloud. Then user adds a new transaction t2 to account a1 on device B, before the device receives the change made in step 1 from cloud. Since a1 hasn't been deleted on device B, the operation should succeed locally. The device tries to save the change to cloud too. My questions: Q1) Will device B be able to save the change in step 2 to cloud? I hope it would fail, because otherwise it would lead to inconsistent data. But I find the following in CKModifyRecordsOperation doc (emphasis mine), which implies CloudKit allows invalid reference: During a save operation, CloudKit requires that the target record of the parent reference, if set, exists in the database or is part of the same operation; all other reference fields are exempt from this requirement. (BTW, I think the fact that, when using CloudKit, Core Data requires all relations must be optional also indicates that CloudKit can't guarantee relation is always valid, though I think that is mainly an issue on client side caused by data transfer size. The above example, however, is different in that it's an issue on cloud side - the data on cloud is inconsistent). I also find the following in the document. However, I don't think it helps in the above example, because IIUC CloudKit can only detect conflict when the changes on the same record but the changes in step 1 and step 2 are on different records. Because records can change between the time you fetch them and the time you save them, the save policy determines whether new changes overwrite existing changes. By default, the operation reports an error when there’s a newer version on the server. If the above understanding is correct, however, I don't understand why the same document has the following requirement, which implies CloudKit doesn't allow invalid reference: When creating two new records that have a reference between them, use the same operation to save both records at the same time. Q2) Suppose CloudKit allows invalid reference on cloud side (that is, device B successfully saves the change in step 2 to cloud) , I wonder what's the best practice to deal with it? I think the issue is different from the optional relation requirement in Core Data when using CloudKit, because in that case the data is consistent on cloud side and eventually the client will receive complete data. In the above example, however, the data on cloud is inconsistent so the client has to remedy it somehow (although client has little information helping it). One approach I think of is to avoid the issue in the first place. My idea is to maintain a counter in the database and requires client to increase the counter (it's not Lamport clock. BTW, is it possible to use Lamport clock in this case?) when making any change. This should help CloudKit to detect conflict (though I can't think out a good strategy on how client should deal with it. A simple one is perhaps to prompt user to select one copy). However, this approach effectively uses cloud as a centralized server, which I suspect isn't the typical way how people use CloudKit, and it requires clients to maintain local counter value in various situations. I wonder what's the typical approach? Am I missing something? Thanks for any help.
2
0
902
Oct ’24
How to "Keep on My iPhone" after disabling iCloud for my app using Core Data
I have Core Data setup with a NSPersistentCloudKitContainer as my container, I've added a container identifier and I see my data on CloudKit's database here when I use "Act As iCloud Account". Here's what I have under capabilities in Xcode However, on my device when I go to Settings > Apple Account > iCloud > Saved to iCloud and switch off my app, all the data saved to Core Data is removed. I suspected this working as intended. When I switch it back on, all the data comes back. However (x2), the support page here says it should remain on the device: When you turn it off, the app no longer connects with iCloud, so your data exists only on your device Am I missing something in how I integrated Core Data in Xcode? Do I need to explicitly configure something with Apple's SDK to get the behavior described in the support page? I've noticed for some of Apple's apps, when you switch off iCloud there's an action sheet asking what you'd like to do with the local data. I figured this was Apple's magic without sharing especially since the buttons looked different Stocks Safari Contacts However (x3), not all apps that had this option offered "Keep on My iPhone", so perhaps the supported behavior is to remove what's on the device and these Apple apps implemented their own support to keep a copy on the device. Reminders I've tried testing some 3rd-party apps but couldn't convince myself they were using Core Data with iCloud enabled. Instead, it looked like they were using iCloud as a backup
1
1
923
Nov ’24
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
974
Jan ’25
Core Data CloudKit stops syncing after incomprehensible archive error
Ive been getting this error on an app in the dev environment since iOS16. it continues to happen in the latest iOS release (iOS18). After this error/warning, CoreData_CloudKit stops syncing and the only way to fix it is to delete the app from all devices, reset the CloudKit dev environment, reload the schema and reload all data. im afriad that if I ever go live and get this error in production there won't be a way to fix it given I cant go and reset the production CloudKit environment. It doesn't happen straight away after launching my app in a predictable manner, it can take several weeks to happen. Ive posted about this before here and haven't got a response. I also have a feedback assistant issue submitted in 2022 as part of ios16 beta that is still open: FB10392936 for a similar issue that caused the same error. would like to submit a code level support query but it doest seem to have anything to do with my code - but rather the Apple core data CloudKit syncing mechanism. anyone have any similar issues or a way forward? > error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _requestAbortedNotInitialized:](2200): <NSCloudKitMirroringDelegate: 0x301e884b0> - Never successfully initialized and cannot execute request '<NSCloudKitMirroringImportRequest: 0x3006f5a90> D823EEE6-EFAE-4AF7-AFED-4C9BA708703B' due to error: Error Domain=NSCocoaErrorDomain Code=4864 "*** -[NSKeyedUnarchiver _initForReadingFromData:error:throwLegacyExceptions:]: incomprehensible archive (0x53, 0x6f, 0x6d, 0x65, 0x20, 0x73, 0x61, 0x6d)" UserInfo={NSDebugDescription=*** -[NSKeyedUnarchiver _initForReadingFromData:error:throwLegacyExceptions:]: incomprehensible archive (0x53, 0x6f, 0x6d, 0x65, 0x20, 0x73, 0x61, 0x6d)}
3
0
1k
Nov ’24
Swiftdata + Cloudkit + Mac OS how to configure for existing Swift Data store
Hi, I have a mac os app that I am developing. It is backed by a SwiftData database. I'm trying to set up cloudkit so that the app's data can be shared across the user's devices. However, I'm finding that every tutorial i find online makes it sound super easy, but only discusses it from the perspective of ios. The instructions typically say: Add the iCloud capability. Select CloudKit from its options. Press + to add a new CloudKit container, or select one of your existing ones. Add the Background Modes capability. Check the box "Remote Notifications" checkbox from its options. I'm having issue with the following: I don't see background modes showing up or remote notifications checkbox since i'm making a mac os app. If i do the first 3 steps only, when i launch my app i get an app crash while trying to load the persistent store. Here is the exact error message: Add the iCloud capability. Select CloudKit from its options. Press + to add a new CloudKit container, or select one of your existing ones. Add the Background Modes capability. Check the box "Remote Notifications" checkbox from its options. Any help would be greatly appreciated. var sharedModelContainer: ModelContainer = { let schema = Schema([One.self, Two.self]) let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false) do { return try ModelContainer(for: schema, configurations: [modelConfiguration]) } catch { fatalError("Could not create ModelContainer: \(error)") } }() The fatal error in the catch block happens when i run the app.
7
2
1.9k
Nov ’24
iCloud CoreData integration Issue
Hi, I have configured my ios app with iCloud Coredata sync. I have already checked bundleId, containerId, and cloud login on the device. I am getting the following error. error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _performSetupRequest:]_block_invoke(1242): <NSCloudKitMirroringDelegate: 0x600003d085a0>: Failed to set up CloudKit integration for store: <NSSQLCore: 0x105814630> (URL: file:///Users/santoshsingh/Library/Developer/CoreSimulator/Devices/B49DDBBB-6111-4664-897C-08976854137E/data/Containers/Data/Application/55E67DB0-8CAE-416D-A873-161443FA690F/Library/Application%20Support/default.store) <CKError 0x600000c786f0: "Partial Failure" (2/1011); "Failed to modify some record zones"; uuid = EC168AB2-FDDD-47C6-B6E1-8C6A52C11F55; container ID = "iCloud.com.AmeristarFence.PerimeterInSite"; partial errors: { com.apple.coredata.cloudkit.zone:defaultOwner = <CKError 0x600000c71ec0: "Permission Failure" (10/2007); server message = "Invalid bundle ID for container"; op = FED32AB88A4F36CC; uuid = EC168AB2-FDDD-47C6-B6E1-8C6A52C11F55> }> CoreData: CloudKit: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _finishedRequest:withResult:]: Finished request: <NSCloudKitMirroringDelegateSetupRequest: 0x600002161c70> 26F773DB-4986-430A-A3FF-AC39B9390223 with result: <NSCloudKitMirroringResult: 0x600000c72130> storeIdentifier: CAC05ADB-DC9A-4CC5-9530-91FDDEEC7DD2 success: 0 madeChanges: 0 error: <CKError 0x600000c786f0: "Partial Failure" (2/1011); "Failed to modify some record zones"; uuid = EC168AB2-FDDD-47C6-B6E1-8C6A52C11F55; container ID = "iCloud.com.AmeristarFence.PerimeterInSite"; partial errors: { com.apple.coredata.cloudkit.zone:defaultOwner = <CKError 0x600000c71ec0: "Permission Failure" (10/2007); server message = "Invalid bundle ID for container"; op = FED32AB88A4F36CC; uuid = EC168AB2-FDDD-47C6-B6E1-8C6A52C11F55> }> CoreData: CloudKit: CoreData+CloudKit: -[NSCloudKitMirroringDelegate checkAndExecuteNextRequest]: <NSCloudKitMirroringDelegate: 0x600003d085a0>: Checking for pending requests. CoreData: CloudKit: CoreData+CloudKit: -[NSCloudKitMirroringDelegate checkAndExecuteNextRequest]_block_invoke(3569): <NSCloudKitMirroringDelegate: 0x600003d085a0>: No more requests to execute. error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate recoverFromError:]: <NSCloudKitMirroringDelegate: 0x600003d085a0> - Attempting recovery from error: <CKError 0x600000c786f0: "Partial Failure" (2/1011); "Failed to modify some record zones"; uuid = EC168AB2-FDDD-47C6-B6E1-8C6A52C11F55; container ID = "iCloud.com.AmeristarFence.PerimeterInSite"; partial errors: { com.apple.coredata.cloudkit.zone:defaultOwner = <CKError 0x600000c71ec0: "Permission Failure" (10/2007); server message = "Invalid bundle ID for container"; op = FED32AB88A4F36CC; uuid = EC168AB2-FDDD-47C6-B6E1-8C6A52C11F55> }> error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _recoverFromPartialError:forStore:inMonitor:]_block_invoke(2775): <NSCloudKitMirroringDelegate: 0x600003d085a0>: Found unknown error as part of a partial failure: <CKError 0x600000c71ec0: "Permission Failure" (10/2007); server message = "Invalid bundle ID for container"; op = FED32AB88A4F36CC; uuid = EC168AB2-FDDD-47C6-B6E1-8C6A52C11F55; container ID = "iCloud.com.AmeristarFence.PerimeterInSite"> error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _recoverFromPartialError:forStore:inMonitor:]: <NSCloudKitMirroringDelegate: 0x600003d085a0>: Error recovery failed because the following fatal errors were found: { "<CKRecordZoneID: 0x600000c720a0; zoneName=com.apple.coredata.cloudkit.zone, ownerName=defaultOwner>" = "<CKError 0x600000c71ec0: "Permission Failure" (10/2007); server message = "Invalid bundle ID for container"; op = FED32AB88A4F36CC; uuid = EC168AB2-FDDD-47C6-B6E1-8C6A52C11F55; container ID = "iCloud.com.AmeristarFence.PerimeterInSite">"; }
1
0
984
Oct ’24
Unable to load saved game data in Simulator since update to XCode 16
The update was the only change I can see. Which I did just the other day. I did log on to iCloud.com, I also looked at Apple Developer. I didn't see any additional updates of terms that needed to be accepted. I am sure to log into iCloud on the simulator. It seems to stay logged in. Until I fetchSavedGames. Where I have it exit at 20 seconds due to timing out. Then when I go back to check my account in Settings, it's asking to "Sign in to iCloud" again. It does work properly on a device. So it doesn't stay logged into iCloud on the simulator but it seems like the fetchSavedGame from GKLocalPlayer is what resets that. Any help or suggestions would be appreciated. Thanks.
1
0
666
Oct ’24
SwiftData: Predicate using optional Codable enum
Hello, I'm currently developing an app using SwiftData. I want the app to use CloudKit to sync data, so I made sure all my model properties are optional. I've defined a Codable enum as follows: enum Size: Int, Codable { case small case medium case large } I've defined a Drink SwiftData model as follows: @Model class Drink { var name: String? var size: Size? init( name: String? = nil, size: Size? = nil ) { self.name = name self.size = size } } In one of my Views, I want to use a @Query to fetch the data, and use a Predicate to filter the data. The Predicate uses the size enumeration of the Drink model. Here is the code: struct DrinksView: View { @Query var drinks: [Drink] init() { let smallRawValue: Int = Size.small.rawValue let filter: Predicate<Drink> = #Predicate<Drink> { drink in if let size: Size = drink.size { return size.rawValue == smallRawValue } else { return false } } _drinks = Query(filter: filter) } var body: some View { List { ForEach(drinks) { drink in Text(drink.name ?? "Unknown Drink") } } } } The code compiles, but when I run the app, it crashes with the following error: Thread 1: Fatal error: Couldn't find \Drink.size!.rawValue on Drink with fields [SwiftData.Schema.PropertyMetadata(name: "name", keypath: \Drink.name, defaultValue: nil, metadata: nil), SwiftData.Schema.PropertyMetadata(name: "size", keypath: \Drink.size, defaultValue: nil, metadata: nil)] How can I filter my data using this optional variable on the Drink model? Thanks, Axel
0
3
601
Oct ’24
Document-Based App with MVVM
ExampleCode.txt Dear all, I made an app for computing Finite Element Analysis of electric motors. I (think I) managed to follow the MVVM principle by not exposing the model to the views. Now, my goal is to be able to use documents, each representing a different motor. I want to have my files saved on iCloud, and I want to be able to read plain text from it, so some other code (i.e. python) can create new configurations, even though this app is made for building, graphically. Before trying to work with FileDocument, my class ViewModel: ObservableObject had properties with Published, like @Published var staOD = 80.0, and I would have views with TextFields to change these values. Now, I’m trying to blend in FileDocument, and I’m lost. I don’t know how I should work with my data. Under the “Separation of Concerns”, I guessed that: ViewModel: Should handle computations, updates, and application logic. Document: Should focus on data persistence and encapsulate data to be saved/loaded as a document. My ViewModel looks a bit strange to me, and I’m not sure I’m updating it the right way. I have around 100 parameters, I’m afraid I’m updating these parameters too often and unnecessarily every parameter at the same time, even when only one value is changed in the document. What I’m asking: Clarifications on how to work with FileDocument in my case of MVVM (I’m open to change the entire workflow, my main knowledge is on the Model built in Swift, but not SwiftUI) Why isn’t the computed area on the DocumentView at the right value when I open a document? I would like to open documents and have it in the “right” state. In reality, I’m computing an image of the electric motor, and it would be nice to open the document and see the “real” image, and not a dummy image before I can validate the geometry. I have these warnings popping every time I open a document and that scares me, especially because I want ideally to use swift 6 in the coming future, with concurrency the right way. Publishing changes from background threads is not allowed; make sure to publish values from the main thread (via operators like receive(on:)) on model updates. Thanks a lot for your help, Guillaume I made an example/simplified code that has all the logic. I can't show the entire code in this prompt due to space limitation. Therefore, I put everything (184 lines) in a single Swift file for you to download. You can just create a Multiplatform Document App. Remove all files except the ...App file, in which you can paste the content of the shared swift file. Run on iPhone simulator. Development environment: Xcode 16, macOS 15 Run-time configuration: iOS 18, macOS 15 Open the app, click on "New motor" You will see "Computed area: 3'063..." Click on "Geometry", change "Stator OD" to 60 instead of 80. Click on "Save" button, now Computed area is 863... Click on "Cancel" button, and reopen the same document Problem: area is again 3'063 while when you open Geometry, you see that "Stator OD" is rightfully 60.
1
0
1.2k
Oct ’24
How can the owner access a zone he shared on cloudkit?
Using this Apple repository as a basis https://github.com/apple/sample-cloudkit-zonesharing I created and verified the shared zone and the same zone is private for the person who shared it and shared for the person who received it, so aren't they the same zones? [same zone but different id?] I can make the person who shared the zone (owner) access the zone as a .shared scope just like the person who was shared.
1
0
474
Oct ’24
CloudKit error: Client went away before operation XXXXXX could be validated; failing
All of a sudden my app started getting this CloudKit error, and it happens to a lot of users. I had no changes to cloud sync for months and really surprised by seeing this. What confuses me even more, is that there is no information on the web about this kind of error. I have no idea what causes it and how to solve it. Would love to get any feedback from the CloudKit engineer. Client went away before operation 27761871408C460A could be validated; failing { "NSUnderlyingError": "<CKUnderlyingError 0x600002573f30: \"ClientInternalError\" (2005); \"Client went away before operation 27761871408C460A could be validated; failing\">", "CKErrorDescription": "Client went away before operation 27761871408C460A could be validated; failing", "NSDebugDescription": "CKInternalErrorDomain: 2005", "NSLocalizedDescription": "Client went away before operation 27761871408C460A could be validated; failing" } Seems to happen only on macOS.
2
0
1k
Oct ’24
Querying modifiedTimestamp in CloudKit
I have a requirement to get all records changed after a certain date. I have set modifiedTimestamp as Queryable, but when I attempt to do any query at all using the following operators: > < >= <= no results are returned. I have confirmed there are records that should be returned. The only operator that works is == and !=. I have tried the following: NSPredicate(format: "modificationDate > %@", lastFetched as NSDate) NSPredicate(format: "___modTime > %@", lastFetched as NSDate)
1
0
832
Oct ’24
Cloudkit issue | development environment
Hello! I deleted an index on the cloudkit console of a container in development environment and re-added it again with the same name. After that my app has been giving error on development environment. The live version is working fine as I haven't deployed the changes.. Any idea what can cause this issue and is there a way to fix it? Thank you
1
0
693
Oct ’24
error sharing url on cloudkit share
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."
0
0
556
Sep ’24
loudKit Containers are not being created or connecting back do apple dev besides the default container
Every new container i create for cloudkit doesn't work and or connect back to my icloud dev account. Here are the errors: Communication with Apple failed. An iCloud Container with Identifier 'iCloud.icloud.com.plantclock.backup' is not available. Please enter a different string. Provisioning profile "iOS Team Provisioning Profile: CGL.CannaGrowLog" doesn't support the iCloud.icloud.com.plantclock.backup iCloud Container. Provisioning profile "iOS Team Provisioning Profile: CGL.CannaGrowLog" doesn't match the entitlements file's value for the com.apple.developer.icloud-container-identifiers entitlement. STEPS TO REPRODUCE Went into xcode > Project name > targets > icloud > containers > + sign and anytime i try to add it fails with the above issues. Also, going into apple dev website has no option to even see or add containers.
1
0
575
Sep ’24