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.

CloudKit Documentation

Posts under CloudKit tag

324 Posts
Sort by:
Post not yet marked as solved
1 Replies
199 Views
Hey everyone! I'm starting a new Multiplatform application with Core Data and CloudKit checked off. Before continuing I want to make sure the data is persisting between devices BUT can't figure out how to test that with the simulator. I can run the app on my Mac (under my apple account), can't run it on my phone (didn't download the beta), and when I try to log into the simulator with my Apple ID it gives me a "Verification Failed - An unknown error occurred". How do you test synced data between simulated devices???
Posted Last updated
.
Post not yet marked as solved
9 Replies
3.1k Views
Any insights on how to incorporate CloudKit (or CoreData) in the WidgetKit extension? Where in the WidgetKit api do I make the asynchronous call to load the data to be available for the TimelineProvider?
Posted
by cristosv.
Last updated
.
Post marked as solved
1 Replies
194 Views
The com.apple.developer.icloud-container-environment provides the option to set "the development or production environment to use for the iCloud containers." My app uses Core Data, and I have implemented NSPersistentCloudKitContainer. When I am not working on schema changes, I would like my local development builds to still access the production Core Data store. However, setting this entitlement to "Production" has not produced this result... the container is still listed as 'Staging' and I can see in the CloudKit Console that the Development container is being used. Does this entitlement only apply to direct use of CloudKit, and not to NSPersistentCloudKitContainer? If it doesn't apply to the latter, is there another way to direct NSPersistentCloudKitContainer to use the Production container? This is an iOS app though I am beginning work on a macOS version and would like to be able to do this in both environments.
Posted
by babbage.
Last updated
.
Post not yet marked as solved
0 Replies
107 Views
I want to add Core Data/CloudKit data persistence to my app. Currently my app only uses local on device @AppStorage. Looking for best approach to bring in @FetchRequest functionality for my views, and tie my model data into Core Data and CloudKit.  In my app currently (without Core Data) my content view has an instance of my view model (separate file) accessed using an Environment Object. I use local @AppStorage persistence. See below for my Current app architecture: In my lab this week, i got suggestions that I can modify my app structure to incorporate Core Data + CloudKit. Would the following structure work?:
Posted Last updated
.
Post marked as solved
3 Replies
445 Views
I found out that for some reason, /Library/Developer/CoreSimulator/Volumes/watchOS_20R5287q/Library/Developer/CoreSimulator/Profiles/Runtimes/watchOS 9.0.simruntime/Contents/Resources/RuntimeRoot/usr/lib/swift/libswiftCloudKit.dylib is not a file, but a symlink to /System/Library/Frameworks/CloudKit.framework/CloudKit - which is a folder, not a file, and as a result, any app that uses CloudKit crashes instantly after start on my WatchOS 9 and iOS 16 simulators. On WatchOS 8.5 and iOS 15.5 sim everything works. Can you confirm if this is a known bug? I tried redownloading the simulators, but the result is same.
Posted Last updated
.
Post not yet marked as solved
0 Replies
131 Views
I use NSPersistentCloudKitContainer to synchronize data between iOS and macOS. After installing the app, it takes long (sometimes up to an hour) for all data to become available. Related to this, I have a few questions: Synchronization seems only to take place when the app runs in the foreground. Is there a way to keep the app synchronizing when it is brought to the background? I have enabled remote notifications and use registerForRemoteNotifications in my app delegate (via UIApplicationDelegateAdaptor). I haven't yet experimented with background processing. Should I do that, and can you point me to some references? Is there a way to check whether the local-stored data matches what's available on the server? E.g. checking whether a (local-stored) NSPersistentHistoryToken matches the latest NSPersistentHistoryToken on the server. Internally NSPersistentCloudKitContainer knows, as I can see log events popping up saying that there are no new data to mirror. I would like to know this to inform the user that synchronization still takes place. Currently, users are complaining about missing data, which is just not available yet. Thanks!
Posted Last updated
.
Post marked as solved
5 Replies
350 Views
I'm getting ready to release a new app that uses CloudKit. I just deployed my Development schema to Production in CloudKit dashboard. Is there a way to run my app from Xcode using the CloudKit Production environment for testing? Details of how to test in the production environment are described here: https://developer.apple.com/library/archive/documentation/DataManagement/Conceptual/CloudKitQuickStart/TestingYourApp/TestingYourApp.html But would be faster (and easier for debugging potential issues) if I could select tell Xcode to use the production environment when running from the debugger. Is this supported? Thanks
Posted Last updated
.
Post not yet marked as solved
1 Replies
311 Views
Hi, I want to activate/deactivate the CloudKit Sync during App runtime in a user settings view. Basically this works fine. Every time I toggle between the NSPersistentContainer and the NSPersistentCloudKitContainer, I increase the persistence.persistenceContainerReloaded attribute and the whole view hierarchy will be reloaded. Thus all changes are passed through the whole app. During the reload phase I have to load a new persistence store by container.loadPersistentStores(...). Unfortunately, I cannot remove the old persistence store before loading the new one. The app crashes immediately, because the store and viewContext is still in use. Therefore, I just create a new one and trigger the reload. Afterwards every view is using the new viewContext. But somewhere in the background there is still the old persistence store with CloudKit Sync active and pushes every local change to the cloud. Changes on the cloud from other devices are not received anymore. Does someone has any idea, how to correctly unload a PersistentStore (replace NSPersistentCloudKitContainer by NSPersistentContainer) in a SwiftUI based app? @main struct TargetShooterApp: App {     @StateObject var persistence: Persistence = Persistence.shared     var body: some Scene {         WindowGroup {             ContentView()                 .environment(\.managedObjectContext, persistence.container.viewContext)                 .id(persistence.persistenceContainerReloaded)         }     } }
Posted Last updated
.
Post not yet marked as solved
1 Replies
164 Views
When I add or remove records to a share's hierarchy using CKModifyRecordsOperation, do I need to include the share in the recordsToSave argument of one of the convenience initializers or the property recordsToSave property?
Posted Last updated
.
Post not yet marked as solved
3 Replies
568 Views
Hi, I'm currently developing a SwiftUI based app with Core Data and CloudKit sync with the NSPersistentCloudKitContainer. I found different solutions how to toggle CloudKit sync of the Core Data during runtime. The basic idea of these solutions is the following. instantiate a new NSPersistentCloudKitContainer set storeDescription.cloudKitContainerOptions = nil load persistence store Some solutions recommend to restart the app manually to avoid exactly my problem. Issues So far so good. How can I distribute the new viewContext through my app during runtime. In the main App I distributed the viewContext during startup via @Environment(\.managedObjectContext) and it seems not be updated automatically after a reinitialization of NSPersistentCloudKitContainer. var body: some Scene {   WindowGroup {             ContentView()                 .environment(\.managedObjectContext, persistence.container.viewContext)         } } After deactivating the CloudKit sync I receive the following error when I try to add a new entity. [error] warning: Multiple NSEntityDescriptions claim the NSManagedObject subclass 'TestEntity' so +entity is unable to disambiguate. Any ideas? Regards Sven
Posted Last updated
.
Post marked as solved
1 Replies
170 Views
Hello, I want to create an app that I’ll be the only one that uses it. Since apple requires 99$ a year for deployment, Is there a free way of running my app on my iPhone? The plan is to use Apple’s CloudKit with swift UI. If there is no free way to deploy the app for myself only, what would be your suggestion then ? Thanks
Posted Last updated
.
Post not yet marked as solved
0 Replies
90 Views
Have a simple, or what I think is simple view, that includes the below code struct ContentView: View {     @StateObject var coordinator = Coordinator() var body: some View {       if coordinator.sharedAlbumPermission { sharedAlbumView() } else { permissionToAlbumView() } } My app has permission already for "All Photos". The issue I am running into is that the "permissionToAlbumView()" displays for about 5 seconds before "sharedAlbumView()" displays. When I change permission to "None" I only see "permissionToAlbumView()". When I update in settings then switch to my app the "sharedAlbumView()" displays right away. Not sure why "permissionToAlbumView()" would display when permission is already given. I think the issue that the .sharedAlbumPermission is giving wrong value first and then updating but I could be wrong. If there is another and better way to code this I would greatly appreciate as new to Swift. Have tried onAppear and onDisappear but does not seem to work either.
Posted Last updated
.
Post marked as solved
2 Replies
304 Views
So I created a program without selecting “use core data” and realized after trying to make a persistence data storage that it helps very much so I created a new program and selected it this time and copied everything over. It provided a file called “Persistence” and the contentView file had a bunch of stuff already filled in (Also something called the title of the program). I have the data I need saved to the persistent data storage narrowed down to a singular array, but none of the videos I found online showed this version of xcode that supplied a “Persistence” file when using core data so I’m unsure how to use it. I will provide the contentView and Persistence file for context. The array I need saved is called mainList in contentView. ContentView: import SwiftUI import CoreData struct ContentView: View {     var mainList = [RecipeList(),RecipeList(),RecipeList(),RecipeList(),RecipeList()]          @Environment(\.managedObjectContext) private var viewContext     @FetchRequest(         sortDescriptors: [NSSortDescriptor(keyPath: \Item.timestamp, ascending: true)],         animation: .default)     private var items: FetchedResults<Item>     var body: some View {         NavigationView {             List {                 ForEach(items) { item in                     NavigationLink {                         Text("Item at \(item.timestamp!, formatter: itemFormatter)")                     } label: {                         Text(item.timestamp!, formatter: itemFormatter)                     }                 }                 .onDelete(perform: deleteItems)             }             .toolbar {                 ToolbarItem(placement: .navigationBarTrailing) {                     EditButton()                 }                 ToolbarItem {                     Button(action: addItem) {                         Label("Add Item", systemImage: "plus")                     }                 }             }             Text("Select an item")         }     }     private func addItem() {         withAnimation {             let newItem = Item(context: viewContext)             newItem.timestamp = Date()             do {                 try viewContext.save()             } catch {                 // Replace this implementation with code to handle the error appropriately.                 // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.                 let nsError = error as NSError                 fatalError("Unresolved error \(nsError), \(nsError.userInfo)")             }         }     }     private func deleteItems(offsets: IndexSet) {         withAnimation {             offsets.map { items[$0] }.forEach(viewContext.delete)             do {                 try viewContext.save()             } catch {                 // Replace this implementation with code to handle the error appropriately.                 // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.                 let nsError = error as NSError                 fatalError("Unresolved error \(nsError), \(nsError.userInfo)")             }         }     } } private let itemFormatter: DateFormatter = {     let formatter = DateFormatter()     formatter.dateStyle = .short     formatter.timeStyle = .medium     return formatter }() struct ContentView_Previews: PreviewProvider {     static var previews: some View {         ContentView().environment(\.managedObjectContext, PersistenceController.preview.container.viewContext)     } } Persistence: import CoreData struct PersistenceController {     static let shared = PersistenceController()     static var preview: PersistenceController = {         let result = PersistenceController(inMemory: true)         let viewContext = result.container.viewContext         for _ in 0..<10 {             let newItem = Item(context: viewContext)             newItem.timestamp = Date()         }         do {             try viewContext.save()         } catch {             // Replace this implementation with code to handle the error appropriately.             // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.             let nsError = error as NSError             fatalError("Unresolved error \(nsError), \(nsError.userInfo)")         }         return result     }()     let container: NSPersistentCloudKitContainer     init(inMemory: Bool = false) {         container = NSPersistentCloudKitContainer(name: "ReciStorage")         if inMemory {             container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")         }         container.loadPersistentStores(completionHandler: { (storeDescription, error) in             if let error = error as NSError? {                 // Replace this implementation with code to handle the error appropriately.                 // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.                 /*                  Typical reasons for an error here include:                  * The parent directory does not exist, cannot be created, or disallows writing.                  * The persistent store is not accessible, due to permissions or data protection when the device is locked.                  * The device is out of space.                  * The store could not be migrated to the current model version.                  Check the error message to determine what the actual problem was.                  */                 fatalError("Unresolved error \(error), \(error.userInfo)")             }         })         container.viewContext.automaticallyMergesChangesFromParent = true     } } Image showing the thing named the title of the program that I’m certain is relevant to the persisting data storage: Also I’m unsure what I need to replace those comments with and what subclasses I should add to existing swift files like “codable” for example. Any help would be greatly appreciated.
Posted Last updated
.
Post not yet marked as solved
0 Replies
112 Views
I have several different apps that I'd like to share a personal core data store with on the same device and across devices. I've been experimenting with NSPersistentCloudKitContainer, which seems to work, but it can take a while to sync and it's not clear when it has. I have also experimented with using app groups where the SQLite file is placed in the app group so that changes are immediately available to other apps on the device. My question is whether it is better to do one or the other or both. Will two apps open on the same device accessing the shared SQLite cause conflict issues? Do I even need to sync data with cloudKit if I'm already syncing with a shared group? Using NSPersistentCloudKitContainer alone means that each app will be syncing its own copy of the data locally, which doesn't seem very efficient and again I don't know if it's synched when I open the other app up. But I have seen conflicts when i have both apps open at the same time. Is there a foolproof way to prevent conflicts when one app goes into the background?
Posted Last updated
.
Post not yet marked as solved
14 Replies
2.7k Views
When I use NSPersistentCloudKitContainer to sync data, I receive error Code=134421/134406 Import failed because applying the accumulated changes hit an unhandled exception. iOS/iPadOS 15 beta 5 - iOS/iPadOS 15 beta 7(latest) When this error appears, data can not be import/merged from iCloud. Delete app and reinstall is not working. Same momd on macOS 12(Catalyst, with full data upgrated from macOS 11) works fine. Maybe a system bug? Merge Policy: context.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy context.automaticallyMergesChangesFromParent = true Console log here: CoreData: error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _requestAbortedNotInitialized:](1826): <NSCloudKitMirroringDelegate: 0x282f3c180> - Never successfully initialized and cannot execute request '<NSCloudKitMirroringExportRequest: 0x2815d8180> B7974D4D-C5DA-413E-AE3B-072C88D38D47' due to error: Error Domain=NSCocoaErrorDomain Code=134421 "Import failed because applying the accumulated changes hit an unhandled exception." UserInfo={NSLocalizedFailureReason=Import failed because applying the accumulated changes hit an unhandled exception., NSUnderlyingException=*** NSAllocateMemoryPages(103626821) failed} CoreData: CloudKit: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _finishedRequest:withResult:](2713): Finished request: <NSCloudKitMirroringExportRequest: 0x2815d8180> B7974D4D-C5DA-413E-AE3B-072C88D38D47 with result: <NSCloudKitMirroringResult: 0x281b51060> success: 0 madeChanges: 0 error: Error Domain=NSCocoaErrorDomain Code=134406 "Request 'B7974D4D-C5DA-413E-AE3B-072C88D38D47' was aborted because the mirroring delegate never successfully initialized due to error: Error Domain=NSCocoaErrorDomain Code=134421 "Import failed because applying the accumulated changes hit an unhandled exception." UserInfo={NSLocalizedFailureReason=Import failed because applying the accumulated changes hit an unhandled exception., NSUnderlyingException=*** NSAllocateMemoryPages(103626821) failed}" UserInfo={NSLocalizedFailureReason=Request 'B7974D4D-C5DA-413E-AE3B-072C88D38D47' was aborted because the mirroring delegate never successfully initialized due to error: Error Domain=NSCocoaErrorDomain Code=134421 "Import failed because applying the accumulated changes hit an unhandled exception." UserInfo={NSLocalizedFailureReason=Import failed because applying the accumulated changes hit an unhandled exception., NSUnderlyingException=*** NSAllocateMemoryPages(103626821) failed}}
Posted
by lights.
Last updated
.
Post not yet marked as solved
0 Replies
120 Views
I'm trying to retrieve record from the public database of CloudKit. (Swift version 5.6 , Xcode 13.3 and iOS 15.4) From Content.view, I call the function vm.retrieve_T100 of ViewModel.swift. The argument of it is mail address user will input. I've set the print for debug. I want to progress like *1,*2,*3,*3,*3,*4,*5. But Actually It progressed like *1,*2,*5,3,,3,*3,*4. How should I change the program? probably I should stop the way of asynchronous processing, and I should re-write the program in synchronous processing. I don't know how to it. ContentView.swift struct ContentView: View { @EnvironmentObject var vm: ViewModel ..... var body: some View { ..... func mail_choufuku_error_check(_:String) -> Bool { **print("*1 before retrieve_T100 *")** vm.retrieve_T100(in_mail_address: usr.T100_MAIL_ADDRESS) **print("*5 after retrieve_T100 *")** ..... ViewModel.swift import CloudKit final class ViewModel: ObservableObject { private lazy var container = CKContainer(identifier: Config.containerIdentifier) private lazy var database = container.publicCloudDatabase ..... func retrieve_T100(in_mail_address:String) { **print("*2 retrieve_T100:start !!")** let predicate = NSPredicate(format: "MAIL_ADDRESS == %@", in_mail_address) let query = CKQuery(recordType: "T100_T_SCHOOL", predicate: predicate) let queryOperation = CKQueryOperation(query: query) queryOperation.recordMatchedBlock = { record, result in switch result { case .success(let record): **print("*3 retrieve_T100:(A)MAIL_ADDRESS = \**(record["MAIL_ADDRESS"]!)") case .failure(let error): print("*3 retrieve_T100:error = \(error.localizedDescription)") } } queryOperation.queryResultBlock = { result in switch result { case .failure(let error): print("*4 retrieve_T100:(B) Error ...") print(error.localizedDescription) case .success: **print("*4 retrieve_T100:(B) Success ...")** } } database.add(queryOperation) } .... report of display after processing *1 before retrieve_T100 * *2 retrieve_T100:start !! *5 after retrieve_T100 * *3 retrieve_T100:(A)MAIL_ADDRESS = xxxxxxxx *3 retrieve_T100:(A)MAIL_ADDRESS = xxxxxxxx *3 retrieve_T100:(A)MAIL_ADDRESS = xxxxxxxx *4 retrieve_T100:(B) Success ...
Posted Last updated
.
Post not yet marked as solved
0 Replies
102 Views
Hi everyone, we recently integrated UICloudSharingController to share cloudkit records on one of our apps, but we noticed while testing that the icloud share link opens the wrong app on App Store if we invite a participant who has not the app installed on his device. We thought it was because for another our app (app store opens the download page for this app) we basically duplicated the same coredata/cloudkit implementation, forgetting maybe some cloudkit references of the first app and indeed we noticed a wrong icloud container assignment for the second app, which essentially had two containers, the correct one (its own) and the one of the first app (the wrong one). So, we fixed the problem, every app has his own container now and only his own, and we updated the provisional profiles as well, in order to have the correct icloud containers entitlements. Unfortunately the problem persists and after check everything else (containers, app groups, PersistentStoreDescriptions etc.) we don't have any more ideas. What else should we check? Thanks in advance for your suggestions. Some more detail of the issue: If we have the app installed on the device the icloud share link opens the right app. The same icloud share link works properly on Mac Catalyst (the App Store opens the correct app page if we don't have the app installed). The problem is only on iOS.
Posted Last updated
.
Post not yet marked as solved
0 Replies
122 Views
Short version: Is it a terrible hack to use the URLs to remote CKAsset? And are they permanent? I'm building an app that plays sound using AV(Queueu)Player and use CloudKit with CoreData to store the metadata. I was planning to also store the audio assets there, as CKAssets, but it seems like it's not really built for this use case, at least if I want to avoid downloading the files first. What I mean is, AVPlayer plays audio from URLs, but CloudKit doesn't provide a simple way to get the URL for a remote asset, so it would seem I have to first sync the assets down to the local disk, which is what I want to avoid, I would prefer to stream them. There is a way to get the URL, but only using CloudKit JS APIs, as described in [1], but is that a hacky workaround or something we can rely on? And are these URLs permanent? Finally, silly question perhaps, but even if the URLs are solid, can I safely stream audio from them? [1] https://stackoverflow.com/questions/35104247/obtaining-ckasset-url-without-downloading-data
Posted
by Grustaf.
Last updated
.
Post not yet marked as solved
1 Replies
238 Views
Can cloudkit be used as the back end of the app? I want to develop a news app. Can I only use (swiftui + cloudkit)? I am new to develop a app, I hope someone can tell me ,thank you
Posted
by Swift01.
Last updated
.
Post not yet marked as solved
0 Replies
183 Views
I'm a bit stumped on this one. I have two core data entities: Person and Memory. Memory has a people field that is a "to many" relationship to Person, and Person has a memories field that is a "to many" relationship to Memory. I created a PeopleForm view to manage the people associated with a memory. The memory object gets passed in as an @ObservedObject to the view. I want to list the people, but people is an NSSet, so I created a computed property called peopleArray that converts the NSSet to [Person] (and sorts it for good measure). I use the ForEach view with peopleArray to create a list of people. I use the onDelete view modifier to let the user remove a person from the list of people for that memory. The onDelete calls the removePerson function, which looks up the person object in peopleArray by the index, and then passes it to the memory object's removeFromPeople() method. The removeFromPeople() method appears to be what triggers the runtime error. I've ready about exclusivity enforcement, but I can't figure out where I've gone wrong here. The following is a pared down version of my code: struct PeopleForm: View {     @ObservedObject var memory: Memory     @Environment(\.managedObjectContext) var viewContext     @Environment(\.dismiss) var dismiss     private var peopleArray: [Person] {         get {             Array(memory.people as! Set<Person>).sorted {                 $0.displayName < $1.displayName             }         }     }     var body: some View {         NavigationView {             List {                 ForEach(peopleArray) { person in                     Text(person.displayName)                 }                 .onDelete(perform: removePerson)             }             .toolbar {                 ToolbarItem(placement: .confirmationAction) {                     Button("Save") {                         dismiss()                     }                 }                 ToolbarItem(placement: .cancellationAction) {                     Button("Cancel") {                         dismiss()                     }                 }             }         }     }     func removePerson(at offsets: IndexSet) {         offsets.forEach { index in             let person = peopleArray[index]             viewContext.perform {                 memory.removeFromPeople(person)             }         }     } } Editing to note that the stack trace points at the App.main() call. The error does not occur when stepping through the code line by line in the debugger, but I also can't step into the removeFromPeople method that is generated from my data model. If I step through to the removeFromPeople line and resume, the error occurs, so it seems to be something internal to CoreData that is going on here.
Posted
by nicksloan.
Last updated
.