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

CoreData + CloudKit
I am having problems when I first loads the app. The time it takes for the Items to be sync from my CloudKit to my local CoreData is too long. Code I have the model below defined by my CoreData. public extension Item { @nonobjc class func fetchRequest() -> NSFetchRequest<Item> { NSFetchRequest<Item>(entityName: "Item") } @NSManaged var createdAt: Date? @NSManaged var id: UUID? @NSManaged var image: Data? @NSManaged var usdz: Data? @NSManaged var characteristics: NSSet? @NSManaged var parent: SomeParent? } image and usdz columns are both marked as BinaryData and Attribute Allows External Storage is also selected. I made a Few tests loading the data when the app is downloaded for the first time. I am loading on my view using the below code: @FetchRequest( sortDescriptors: [NSSortDescriptor(keyPath: \Item.createdAt, ascending: true)] ) private var items: FetchedResults<Item> var body: some View { VStack { ScrollView(.vertical, showsIndicators: false) { LazyVGrid(columns: columns, spacing: 40) { ForEach(items, id: \.self) { item in Text(item.id) } } } } } Test 1 - Just loads everything When I have on my cloudKit images and usdz a total of 100mb data, it takes around 140 seconds to show some data on my view (Not all items were sync, that takes much longer time) Test 2 - Trying getting only 10 items at the time () This takes the same amount of times the long one . I have added the following in my class, and removed the @FetchRequest: @State private var items: [Item] = [] // CK @State private var isLoading = false @MainActor func loadMoreData() { guard !isLoading else { return } isLoading = true let fetchRequest = NSFetchRequest<Item>(entityName: "Item") fetchRequest.predicate = NSPredicate(format: "title != nil AND title != ''") fetchRequest.fetchLimit = 10 fetchRequest.fetchOffset = items.count fetchRequest.predicate = getPredicate() fetchRequest.sortDescriptors = [NSSortDescriptor(keyPath: \Item.createdAt, ascending: true)] do { let newItems = try viewContext.fetch(fetchRequest) DispatchQueue.main.async { items.append(contentsOf: newItems) isLoading = false } } catch {} } Test 2 - Remove all images and usdz from CloudKit set all as Null Setting all items BinaryData to null, it takes around 8 seconds to Show the list. So as we can see here, all the solutions that I found are bad. I just wanna go to my CloudKit and fetch the data with my CoreData. And if possible to NOT fetch all the data because that would be not possible (imagine the future with 10 or 20GB or data) What is the solution for this loading problem? What do I need to do/fix in order to load lets say 10 items first, then later on the other items and let the user have a seamlessly experience? Questions What are the solutions I have when the user first loads the app? How to force CoreData to query directly cloudKit? Does CoreData + CloudKit + NSPersistentCloudKitContainer will download the whole CloudKit database in my local, is that good???? Storing images as BinaryData with Allow external Storage does not seems to be working well, because it is downloading the image even without the need for the image right now, how should I store the Binary data or Images in this case?
1
0
705
Jan ’25
MAJOR Core Data Issues with iOS 18 and sdk - Data Missing for many users?!
I just released an App update the didn't touch ANYTHING to do with Core Data (nothing changed in our Coredata code for at least 8 months). The update uses SDK for iOS 18 and Xcode 16.2 and the app now requires iOS 18 and was a minor bug patch and UI improvements for recent iOS changes. Since the update we are getting a steady trickle of users on iOS 18, some who allow the App to store data in iCloud (Cloudkit) and others who do not, all reporting that after the update to our recent release ALL their data is gone?! I had not seen this on ANY device until today when I asked a friend who uses the App if they had the issue and it turned out they did, so I hooked their device up to Xcode and ALL the data in the CoreData database was gone?! They are NOT using iCloud. There were no errors or exceptions on Xcode console but a below code returned NO records at all?! Chart is custom entity and is defined as: @interface Chart : NSManagedObject {} let moc = pc.viewContext let chartsFetch = NSFetchRequest<NSFetchRequestResult>(entityName:"Charts") // Fetch all Charts do { let fetchedCharts = try moc.fetch(chartsFetch) as! [Chart] for chart in fetchedCharts { .... } } A break point inside the do on fetchedCharts show there are NO objects returned. This is a serious issue and seems like an iOS 18 thing. I saw some people talking in here about NSFetchRequest issues with iOS 18. I need some guidance here from someone Apple engineer here who knows what the status of these NSFetchrequest bugs are and what possible workarounds are. Becasue this problem will grow for me as more users update to iOS 18.
13
0
1.5k
3w
Database not deploying to CloudKit
I am trying to port my application over to CloudKit. My app worked fine before, but then I made scheme of changes and am trying to deploy to a new container. For some reason, the database is not being created after I create the container through Xcode. I think I have configured the app correctly and a container was created, but no records were deployed. My app current stores data locally on individual devices just fine but they don't sync with each other. That's why I would like to use CloudKit. See screenshot from Xcode of where I have configured the container. I also have background notifications enabled. Also see screenshot from console where the container has been created, but no records have been. Any suggestions would be greatly appreciated. Thank you
7
0
755
Jan ’25
SwiftData data duplication
I've got an application built on top of SwiftData (+ CloudKit) which is published to App Store. I've got a problem where on each app update, the data saved in the database is duplicated to the end user. Obviously this isn't wanted behaviour, and I'm really looking forward to fixing it. However, given the restrictions of SwiftData, I haven't found a single fix for this. The data duplication happens automatically on the first initial sync after the update. My guess is that it's because it doesn't detect the data already in the device, so it pulls all data from iCloud and appends it to the database where data in reality exists.
1
0
649
Jan ’25
SwiftData and CloudKit Development vs. Production Database
Hi, I'm working on a macOS app that utilizes SwiftData to save some user generated content to their private databases. It is not clear to me at which point the app I made starts using the production database. I assumed that if I produce a Release build that it will be using the prod db, but that doesn't seem to be the case. I made the mistake of distributing my app to users before "going to prod" with CloudKit. So after I realized what I had done, I inspected my CloudKit dashboard and records and I found the following: For my personal developer account the data is saved in the Developer database correctly and I can inspect it. When I use the "Act as iCloud account" feature and use one of my other accounts to inspect the data, I notice that for the other user, the data is neither in the Development environment nor the Production environment. Which leads me to believe it is only stored locally on that user's machine, since the app does in fact work, it's just not syncing with other devices of the same user. So, my question is: how do I "deploy to production"? I know that there is a Deploy Schema Changes button in the CloudKit dashboard. At which point should I press that? If I press it now, before distributing a new version of my app, will that somehow "signal" the already running apps on user's machines to start using the Production database? Is there a setting in Xcode that I need to check for my Release build, so that the app does in fact start using the production db? Is there a way to detect in the code whether the app is using the Production database or not? It would be useful so I can write appropriate migration logic, since I don't want to loose existing data users already have saved locally.
3
0
896
Jan ’25
CKSyncEngine API design problems and maintenance status inside Apple?
Something I want to know and all users of CKSyncEngine care about I'm going to build a full stack solution using CKSyncEngine, but what's the near future and the support and maintenance priorities inside Apple for CKSyncEngine? There is only one short video for CKSyncEngine, in 2023, no updates after that, no future plans mentioned. I'm worried that this technology be deprecated or not activity maintained. This is a complex technology, without being activity maintained (or open-sourced) there will be fatal production issues we the developer cannot solve. The CK developer in the video stated that "many apps" were using the framework, but he did not list any. The only named is NSUbiquitousKeyValueStore, but NSUbiquitousKeyValueStore is too simple a use case. I wonder is apple's Notes.app using it, or going to use it? Is SwiftData using it? API Problems The API design seems a little bit tricky, not designed from a user's perspective. handleEvent doesn't contain any context information about which batch. How do I react the event properly? Let's say our sync code and CKSyncEngine, and callbacks are all on a dedicated thread. Consider this: in nextRecordZoneChangeBatch you provided a batch of changes, let's call this BATCH 1, including an item in database with uuid "***" and name "yyy" before the changes are uploaded, there are new changes from many OTHER BACKGROUND THREADS made to the database. item "***"'s name is now "zzz" handle SentRecordZoneChanges event: I get records that uploaded or failed, but I don't know which BATCH the records belong to. How do I decide if i have to mark "***" as finished uploading or not? If I mark *** as finished that's wrong, the new name "zzz" is not uploaded. I have to compare every field of *** with the savedRecord to decide if I finished uploading or not? That is not acceptable as the performance and memory will be bad. Other questions I have to add recordIDs to state, and wait for the engine to react. I don't think this is a good idea, because recordID is a CloudKit concept, and what I want to sync is a local database. I don't see any rational for this, or not documented. If the engine is going to ask for a batch of records, you can get all record ids from the batch?
9
0
916
Jan ’25
NSPersistentCloudKitContainer Import failed (incomprehensible archive)
I am using NSPersistentCloudKitContainer and I decided to add a property to an entity. I accidentally ran try! container.initializeCloudKitSchema(options: []) while using the production container in Xcode (com.apple.developer.icloud-container-environment) which throw a couple of errors and created some FAKE_ records in my production container. So I changed to my development container and ran the try! container.initializeCloudKitSchema(options: []) and now it succeeded. After that I cleaned up the FAKE_ records scattered in production container but in Xcode when I'm running I now get these logs in the console (and I can't seem to get rid of them): error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _importFinishedWithResult:importer:](1398): <PFCloudKitImporter: 0x300cc72c0>: Import failed with 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)} error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate recoverFromError:](2310): <NSCloudKitMirroringDelegate: 0x302695770> - Attempting recovery from 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)} error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _recoverFromError:withZoneIDs:forStore:inMonitor:](2620): <NSCloudKitMirroringDelegate: 0x302695770> - Failed to recover from error: NSCocoaErrorDomain:4864 Recovery encountered the following error: (null):0 error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate resetAfterError:andKeepContainer:](610): <NSCloudKitMirroringDelegate: 0x302695770> - resetting internal state after 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)} error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _requestAbortedNotInitialized:](2198): <NSCloudKitMirroringDelegate: 0x302695770> - Never successfully initialized and cannot execute request '<NSCloudKitMirroringExportRequest: 0x303a52d00> 548CB420-E378-42E5-9607-D23E7A2A364D' 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
1
402
1w
App Automatically Logging Out for Some Users
Hello, We’re experiencing an issue in our app where a subset of users are being logged out automatically without any apparent reason. This is impacting both iOS 16 and iOS 17 users (though it’s hard to confirm if it’s platform-specific). Here’s a breakdown of the situation: Symptoms Some users report being logged out of the app randomly, even after remaining active. The issue doesn’t seem to affect all users—just a specific subset. Users are prompted to log in again, and once they do, the app behaves as expected until the issue recurs.
1
0
368
Dec ’24
Why is data not encrypted on icloud.developer.apple.com when i am using encrypted field
Here is my sample code of integration with iCloud let dbName = "GroceryItem1" let fieldName = "todoTitle1" @objc func saveItem(name: String) { let record = CKRecord(recordType: dbName) record.encryptedValues[fieldName] = name database.save(record) { record, error in if error == nil { DispatchQueue.main.asyncAfter(deadline: .now() + 2) { self.fetchItems() } } else { print("Error saving item: \(error?.localizedDescription ?? "Unknown error")") } } } Now my code works fine but what i don't understand is when i login to icloud.developer.apple.com why am i able to see the data, why is it not encrypted? My database is private as well If i go to record types i can see the recordfield is encrypted as shown in below screenshot
2
0
226
Dec ’24
iCloudKit Unable to Deploy Container to Production Environment
When attempting to deploy schema changes in the iCloudKit Database by clicking the Deploy Schema Changes button, a Confirm Deployment dialog appears, showing an error: “Internal error”. The following error details were observed in the JavaScript console: • description: “The request has failed due to an error.” • headers: undefined • message: “Known response error: The request has failed due to an error.” • result: • code: 400 • detailedMessage: undefined • message: “bad-request” • reason: “Internal error” • redirectUrl: undefined • requestUuid: “0c5b4af2-15c9-425f-87ea-************” • retryAfterSeconds: undefined
2
0
720
Dec ’24
Issues during CloudKit record sharing
I am trying to implement record sharing in my project, but when I try to copy the link on the UICloudSharingController, the sheet closes and the link doesn't get copied. My CloudKitManager function: public func shareTeam(_ team: Team) -> AnyPublisher<CKShare, Error> { Future { [weak self] promise in guard let self = self else { promise(.failure(CloudKitError.unknown)) return } let record = team.toCKRecord() let share = CKShare(rootRecord: record) share[CKShare.SystemFieldKey.title] = "Join \(team.name)" as CKRecordValue share.publicPermission = .readWrite let operation = CKModifyRecordsOperation(recordsToSave: [record, share], recordIDsToDelete: nil) operation.savePolicy = .ifServerRecordUnchanged operation.qualityOfService = .userInitiated operation.modifyRecordsResultBlock = { result in switch result { case .success: promise(.success(share)) case .failure(let error): promise(.failure(error)) } } self.privateDatabase.add(operation) } .eraseToAnyPublisher() } ViewModel function: func shareTeam() { guard let selectedTeam = selectedTeam else { return } CloudKitManager.shared.shareTeam(selectedTeam) .receive(on: DispatchQueue.main) .sink { [weak self] completion in switch completion { case .finished: break case .failure(let error): self?.didError = true self?.error = error } } receiveValue: { share in let sharePresenter = SharePresenter( share: share, container: CloudKitManager.shared.container, teamName: selectedTeam.name, rootRecord: selectedTeam.toCKRecord() ) sharePresenter.presentShareSheet() } .store(in: &cancellables) }
1
0
612
Dec ’24
Get CloudKit records created by specific user
I've been searching all over the web trying to find the proper way to get all records created by a specific user in CloudKit. I am able to get the correct id using: guard let userRecordID = try? await container.userRecordID() else { return } I can see that the id returned is associated with records in my CloudKit dashboard. So I would expect that the following would get those records: let predicate = NSPredicate(format: "%K == %@", #keyPath(CKRecord.creatorUserRecordID), userRecordID) let query = CKQuery(recordType: "CKUser", predicate: predicate) But instead when I use that query it returns nothing. It is successful but with nothing returned... Any ideas why this would be happening? P.S. I have also tried constructing the predicate using the reference, but I get the same result - success with no results. P.S.2 Also worth mentioning that I am trying to get the results from the public database and I have set my CKContainer to the correct container id.
5
0
759
Dec ’24
CloudKit Dashboard error "Failed to execute query"
Something has caused my CloudKit queries to fail. On the dashboard I get an error message "Failed to execute query" when I try to "SORT BY" a field. The field is listed under Indexes as "sortable". For a different field, when I enter the field under "FILTER BY", and before I tap "Query", I get "No results". That field is listed under the Indexes as "queryable". It used to work fine. I have described this further, with screenshots at FB16114560
1
0
336
Dec ’24
CloudKit error - CKErrorRequestRateLimited
First query works fine. If next query comes within 30 seconds of first query it generates a CKErrorRequestRateLimited (error.code==7) error telling me to try after a time such that there would be 30 seconds between queries. <CKError 0x30299dd70: "Request Rate Limited" (7/2061); "Operation throttled by previous server http 503 reply. Retry after 20.5 seconds. (Other operations may be allowed.)"; Retry after 20.5 seconds>
2
0
736
Dec ’24
Significant increase in 'Other' CloudKit errors
Looking at my CloudKit Telemetry console I noticed a significant increase in 'Other' errors recently. These errors are impacting user experience and I really don't know how to better understand the issues that may be occurring due to the "other" category. If I query the logs for "other" errors, only 2 results show up for the week. There are 2500+ errors in the telemetry graph (see attached). Is anyone else experiencing this or does anyone have a suggestion on how I can better understand this issue? Thank you!
0
0
344
Dec ’24