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

Xcode 15 RC - CKError: Account temporarily unavailable due to bad or missing auth token
I have two apps which uses the CloudKit public folder so that my users can access data. There's also a private database for them to save data. One is supposed to be able to access the public database without being logged into an iCloud account. And it was working fine. But now, with the simulator, I get the titled error message. It's fine on a device. But, if I log into the simulator with my iCloud account, I can access the public data.
0
0
399
Sep ’23
CloudKit not working properly in iOS 17 RC
CloudKit was working perfectly in iOS 16. However after updating to iOS 17 RC on my devices iCloud sync no longer works properly. The app has a package called CloudKitSyncMonitor which shows the sync status. Normally it would say Synced with iCloud but on iOS 17 it is either stuck in the Syncing or Sync not started state and the data doesn’t update. This mostly happens after a reinstall of the app. After some time it randomly decides to work until I uninstall the app. I’m really confused what could be the problem if it was working fine on iOS 16 but barely works properly on iOS 17? This is currently the code I have for the DataController: import SwiftUI import CoreData class DataController { var container: NSPersistentCloudKitContainer @AppStorage(wrappedValue:true,"syncEnabled",store:UserDefaults(suiteName: "group.com.ip18.SubManager")) var syncEnabled static let shared = DataController() init() { container = NSPersistentCloudKitContainer(name: "Subscriptions") load(syncEnabled: syncEnabled) } func load(syncEnabled: Bool = true) { container = NSPersistentCloudKitContainer(name: "Subscriptions") let url = URL.storeURL(for: "group.com.ip18.SubManager", databaseName: "Subscriptions") let storeDescription = NSPersistentStoreDescription(url:url) if syncEnabled { storeDescription.cloudKitContainerOptions = NSPersistentCloudKitContainerOptions(containerIdentifier: "iCloud.com.ip18.SubManager") } else { storeDescription.cloudKitContainerOptions = nil } let remoteChangeKey = "NSPersistentStoreRemoteChangeNotificationOptionKey" storeDescription.setOption(true as NSNumber, forKey: remoteChangeKey) storeDescription.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey) container.persistentStoreDescriptions = [storeDescription] container.viewContext.automaticallyMergesChangesFromParent = true /* // Only initialize the schema when building the app with the // Debug build configuration. #if DEBUG do { // Use the container to initialize the development schema. try container.initializeCloudKitSchema(options: []) } catch { // Handle any errors. } #endif */ container.loadPersistentStores(completionHandler: {(storeDescription,error) in if let error = error as NSError? { fatalError("Unresolved error \(error)") } }) } }
4
4
1.3k
Oct ’23
CKQueryOperation returns new cursor, but no results, eventually rejects requests
In my app, I am using CloudKit and one thing I need to do is to query all records of a certain record type. I am creating a CKQueryOperation with the record type I am interested in, leaving the rest to the defaults basically (resultsLimit, desiredKeys, qualityOfService etc). Most times, the app does not return any results at all, but does return a queryCursor, indicating there are more results to fetch. So I add a new CKQueryOperation with a CKQuery created with the returned queryCursor. But the same thing happens again (most of the times) - no results (or maybe a single result) and a new queryCursor. This goes on and on until either all results are returned (which usually is not the case) or CloudKit errors out with "Server rejected the request" (perhaps for rate-limiting reasons?). The same behaviour can be observed when using the CloudKit web API, and it doesn't seem to matter what values I set for resultsLimit, desiredKeys, qualityOfService etc... So, what am I doing wrong? How can I query all records of a record type without errors?
2
0
355
Oct ’23
Initial sync of watchOS app using Core Data and CloudKit
I have an existing iOS/watchOS app that uses a third-party database and WatchConnectivity. For various reasons I am migrating the app to use Core Data with CloudKit. I have everything working using NSPersistentCloudKitContainer. Sync between the iOS and watchOS app are working on my test devices when I start with an empty database. However, I need to import existing user's data when they first install this new version. Some users may have hundreds or thousands of records, but the total database size is under 1-2MB. Data migration/import is working on the iOS side, the Core Data entities are populated on first launch and uploaded to CloudKit (I see in the debug logs that a NSPersistentCloudKitContainer.Event export ends successfully). The problem is launching the watchOS app does not sync the data from CloudKit. I see a import started event but never see it end. I never see any Core Data entities appear on watchOS even after waiting several minutes and re-opening the Watch app multiple times. New entities or modifications made on either app are also not synced. Is the problem just too much data which causes the CloudKit sync to never finish? What are the best practice to populate a watchOS app with initial data from the parent iOS app and keep it in sync with CoreData/CloudKit?
3
1
743
Sep ’23
iPadOS17.8 beta not syncing our app
We use a test iPad to test new versions of our app as well as checking new (beta) versions of iPadOS. Our app - Rendezvous Appointment Book -uses iCloud to sync between the iPad and iPhone. So, when an entry is made on either the iPad or iPhone the entry is automatically synced to the other device(s). So, a user can make a client appointment on one device and it syncs to another iPad or iPhone logged into the same iCloud account. This has worked smoothly for years. But, the latest beta version - 17.8 caused a syncing issue where all the existing data that is stored on the same iCloud account did not sync. We have seen this before. Recently, starting with iPadOS/iOS 16.3 syncing failed for a number of users just on their iPads. The data stored on iCloud disappeared, but the iPhone did sync with iCloud. About 30 users could not get their data to sync at all , but the vast majority did sync. Some users who experienced the problem were able to sync by deleting the app and reinstalling it from the App Store, as per our recovery instructions. Then when version 16.4 was released all syncing worked as well as 16.5 and 16.6 which have worked perfectly. When 17 beta was released we tested again for proper syncing, but ran into the same issue with version 17.3 beta - no sync again. But 17.6 beta did sync. Now, in testing this last Thursday with 17.8 beta the same issue reappeared on our test iPad. We contacted Apple Developer support but have yet to get any resolution (and we are worried that when Apple releases 17 on Sep 11 the syncing issue might still rear its ugly head). Has anyone seen this happen? BTW all other iCloud syncing worked correctly, e.g. Photos, backups, etc.
2
1
804
Jan ’24
Unable to deduplicate both private and public store
I've successfully followed the sample code from Apple: Synchronizing a local store to the cloud to deduplicate entities that are created in the user's private store. However my app also has a public store that needs deduplication and if I enable the NSPersistentStoreRemoteChangeNotificationPostOptionKey for both the private and public store then no deduplication will occur in my private store. This is reproducible every time by not setting NSPersistentStoreRemoteChangeNotificationPostOptionKey for the public store. Has anyone else experienced this and has anyone got a solution to get it to work? Persistence setup code: private static func makeStoreDescription(for database: Database) -> NSPersistentStoreDescription { let url: URL let scope: CKDatabase.Scope let configuration: String switch database { case .private: url = Self.privateStoreURL scope = .private configuration = "Private" case .public: url = Self.publicStoreURL scope = .public configuration = "Public" } let storeDescription = NSPersistentStoreDescription(url: url) storeDescription.cloudKitContainerOptions = .init(containerIdentifier: Config.cloudKitContainerIdentifier) storeDescription.cloudKitContainerOptions?.databaseScope = scope switch database { case .private: storeDescription.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey) storeDescription.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey) case .public: // Uncommented otherwise deduplication doesn't work // storeDescription.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey) // storeDescription.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey) break } storeDescription.configuration = configuration return storeDescription } private static func makeContainer(inMemory: Bool = false, useIcloud: Bool) -> NSPersistentCloudKitContainer { let privateStoreDescription = makeStoreDescription(for: .private) let publicStoreDescription = makeStoreDescription(for: .public) let container = NSPersistentCloudKitContainer(name: "Name", managedObjectModel: managedObjectModel) container.persistentStoreDescriptions = [privateStoreDescription, publicStoreDescription] // Don't save information for future use if running in memory... if inMemory { container.persistentStoreDescriptions.forEach { $0.url = URL(fileURLWithPath: "/dev/null") } } print("useIcloud:", useIcloud) if !useIcloud { container.persistentStoreDescriptions.forEach { $0.cloudKitContainerOptions = nil } } container.loadPersistentStores { storeDescription, error in if let error = error as NSError? { fatalError("Unresolved error \(error), \(error.userInfo)") } print("Loaded store configuration:", storeDescription.configuration ?? "") } #if DEBUG // Use the container to initialize the development schema. // Only necessary whenever changes have been made to the schema. //try! container.initializeCloudKitSchema(options: []) #endif container.viewContext.automaticallyMergesChangesFromParent = true container.viewContext.mergePolicy = NSMergePolicy.mergeByPropertyObjectTrump container.viewContext.transactionAuthor = Self.transactionAuthor if !inMemory { do { try container.viewContext.setQueryGenerationFrom(.current) } catch { fatalError("Failed to pin viewContext to the current generation: \(error)") } } return container }
0
0
342
Sep ’23
Overide App name in iCloud "Manage Storage" list
In our team we have two apps A and B, unfortunately app B was released with iCloud entitlement with selected container ID of the app A. It lead to a problem that our app A displays in iCloud "Manage Storage" list on iOS as app B. Because of that people are loosing all of theirs data as they thing it is app A. App B stores uses only Key-Value storage in iCloud How can we override that name so it displays A again?
0
1
529
Aug ’23
How to upload default-data to the public CloudKit database
I need some help understanding how the public database works in CloudKit. First of all, let me say that I know how to connect and use the private database. In this question I'm not looking for an answer on how to connect to the database at self, only the concept. Here is my confusion. I have a set of images that all users in my app will be using, right now what I'm doing is adding the images directly to the app (an Image Set in Xcode) and then I am pulling them to Core Data and then syncing them to CloudKit. As you can see all images are technically stored in every device using my app and in Core Data/CloudKit, not very efficient. What I would like is to have the images stored in a single place where all uses can pull the images from, in this case CloudKit. I know I can have them somewhere in a private server, but I feel like I would be adding more complexity to my app, so I think using CloudKit is a better option for me. Here is my question. How do I get the images to CloudKit, do I upload them directly to CloudKit and then read from all devices or do I need to first add them to a device and upload to CloudKit from there? Thanks!
2
0
570
Sep ’23
Migrate persistent store from CD to CD+CK
I have an app Im moving over to cloudkit and it works fine on a new instance, but updating to this instance causes a perpetual crash and requires reinstall. I know this is because the persistence object changed. I was just using a normal NSPersistentController now a CK one, and there are two persistent stores, the public and private stores. Is there a way to either migrate the data properly, or atleast wipe the data model before it crashes and have it start anew? (I dont have many users and I know them personally so this would be acceptable)
0
0
305
Aug ’23
Converting a .swiftpm app to a .xcodeproj-based one?
I've decided I want my app, which has been shipped to the App Store, to support CloudKit, but it's a .swiftpm app (so I could work on it on the go on an iPad and Swift Playgrounds). I've taken a half-hearted stab at it (there's more pressing stuff to work on and this is a nice to have for the moment), but is there a way to set up a new workspace in Xcode where I have two targets: a .swiftpm version of the app and a .xcodeproj app so I can enable CloudKit for my app and also ship it to the App Store with the same identifier?
0
1
553
Aug ’23
Usage of CKQueryOperation.recordMatchedBlock and .queryResultBlock
Anyone know the correct usage for CKQueryOperation.recordMatchedBlock and .queryResultBlock? Xcode is telling me to use them as the old .recordFetchedBlock and .queryCompletionBlock are deprecated, but there isn't any documentation to say how they should be used. ChatGPT, Bard etc aren't able to provide a correct answer either: specifically, I need to convert the following to use those methods: operation.recordFetchedBlock = { record in // Convert CKRecord to Core Data object and save to Core Data self.saveToCoreData(record: record) } operation.queryCompletionBlock = { (cursor, error) in // Handle potential errors if let error = error { print("Error syncing first of month records: \(error)") } if let cursor = cursor { // There are more records to fetch for this category, continue fetching self.continueSyncing(cursor: cursor, completion: completion) } else { // Done syncing this category, move to the next sync task completion() } }
1
0
496
Aug ’23
Cloudkit Many to Many relationship not updating on public record with full permissions when updated by user other than creator
I have narrowed my problem down to the many to many relationship between user and group record types. When a user transfers ownership of a group the new admin can change things like privacy (a field) but still only the original owner can leave or remove others. The new admin's use of remove user does nothing and no users can leave besides the creator. All security perms are enabled, and no permission not granted errors arise. I simply end up with two unsynced devices where one user observes themselves as having left, and the other that never will observe it. I can get around this a long way but don't really see why I should have to.
0
0
353
Aug ’23
"This NSPersistentStoreCoordinator has no persistent stores", despite setting up all capabilities
Hi guys, First of all, I'm sorry if this is the wrong place to post this. I'm in the last steps of my task manager app: getting the tasks to sync between devices. However, I get the error "This NSPersistentStoreCoordinator has no persistent stores (unknown). It cannot perform a save operation." What does this error exactly mean? My container is initialised so it should have a persistent store, right? I've also enabled all the proper capabilities I'm pretty sure (eg, I've enabled CloudKit, created a container, enabled background fetch and remote notifications.) Here is the code for my data controller: import CoreData import Foundation class DataController: ObservableObject { let container = NSPersistentCloudKitContainer(name: "TaskDataModel") init() { guard let description = container.persistentStoreDescriptions.first else { fatalError("Container descriptions not loaded") } description.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey) container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy container.viewContext.automaticallyMergesChangesFromParent = true container.loadPersistentStores { description, error in if let error = error { print("Core Data failed to load: \(error.localizedDescription)") } } } } Here is TaskManMain: @main struct TaskManApp: App { @StateObject private var dataController = DataController() var body: some Scene { WindowGroup { MainView() .environment(\.managedObjectContext, dataController.container.viewContext) } } } Here is the full repo if y'all are interested: https://github.com/aabagdi/TaskMan Thanks for any help!
1
0
845
Aug ’23
Cloudkit saving error
Hello, I recently started learning Swift and now I'm using Cloudkit to store user information. I kinda have no idea what I'm doing but I watched this youtube tutorial to save user data and display it in UI instantly with DispatchQueue.main.async but it keeps throwing me an error, saying "No exact matches in call to instance method 'save'" What I want to do is I want users to save a new record and I want this record to be updated instantly and be displayed on the screen. How could I fix this? import Foundation import CloudKit enum RecordType:String { case movie = "Movie" } class SavingMovieViewModel : ObservableObject{ private var database :CKDatabase private var container : CKContainer @Published var movies: [SavingMovieModel] = [] init(container: CKContainer){ self.container = container self.database = container.publicCloudDatabase } func saveMovie(title:String, director: String, stars:String, review: String){ let record = CKRecord(recordType: RecordType.movie.rawValue) let movie = Movie(theTitle: title, theDirector: director, theStars: stars, theReview: review) record.setValuesForKeys(movie.toDictionary()) // saving self.database.save(record) { newRecord, error in. //<-- here is where the error is :( if let error = error{ print(error) } else{ if let newRecord = newRecord{ //<-- this bit is the problem. i need the new record added to be displayed instantly if let movie = Movie.fromRecord(newRecord){ DispatchQueue.main.async { self.movies.append(SavingMovieModel(Movie: movie)) } } } } } } func whatMovies(){ //creating an array of movies var movies: [Movie] = [] let query = CKQuery(recordType: RecordType.movie.rawValue, predicate: NSPredicate(value: true)) database.fetch(withQuery: query) { result in switch result{ case.success(let result): result.matchResults.compactMap{$0.1} .forEach{ switch $0 { case.success(let record): if let movie = Movie.fromRecord(record){ movies.append(movie) } case.failure(let error): print(error) } } DispatchQueue.main.async { self.movies = movies.map(SavingMovieModel.init) } case.failure(let error): print(error) } } } } struct SavingMovieModel{ let movie: Movie var movieId :CKRecord.ID?{ movie.movieId } var title:String{ movie.title } var director:String{ movie.director } var stars:String{ movie.stars } var review:String{ movie.review } } This is the Movie struct for Movie objects import Foundation import CloudKit struct Movie{ var movieId: CKRecord.ID? var title:String var director:String var stars:String var review:String init(movieId: CKRecord.ID? = nil, theTitle:String, theDirector:String, theStars:String, theReview:String){ self.title = theTitle self.director = theDirector self.stars = theStars self.review = theReview self.movieId = movieId } func toDictionary() -> [String:Any]{ return ["title": title, "director" :director, "stars":stars, "review": review] } static func fromRecord(_ record :CKRecord) -> Movie? { guard let title = record.value(forKey:"title") as? String, let director = record.value(forKey:"director") as? String, let stars = record.value(forKey:"stars") as? String, let review = record.value(forKey:"review") as? String else{ return nil } return Movie(movieId: record.recordID, theTitle: title, theDirector: director, theStars: stars, theReview: review) } }
3
0
732
Aug ’23
AppAccountToken is missing
Hello I've problem with transaction payload. If I receive POST App Store notification v2 to my server. In the decoded transaction body is missing appAccountToken field. In the iOS app I've just set token like this: let result = try await product.purchase(options: [ .appAccountToken(UUID.encodeIntAsUUID(Auth.shared.user.idUser)), .simulatesAskToBuyInSandbox(true) ]) Where is the problem?
0
0
574
Aug ’23
Using observableobject in a different View
Hello, I want to use this observableobject that I made in SavingMovieView in MovieView How do I do this...? import SwiftUI import CloudKit struct MovieView: View { @State var showingSavingMovieSheet:Bool = false var body: some View { NavigationView{ ZStack(alignment: .bottomTrailing){ //the list of movies List{ //ForEach(vm.movies) { movies in //} //Your Name Block NavigationLink { // } label: { VStack{ Image("your name") .resizable() .aspectRatio(contentMode: .fill) .cornerRadius(20) Text("Your Name") .fontWeight(.bold) .font(.system(size:20)) } .padding() .background(Image("beige")) } //notting hill block NavigationLink { NottingHillView() } label: { VStack{ Image("notting hill") .resizable() .aspectRatio(contentMode: .fill) .cornerRadius(20) Text("Notting Hill") .fontWeight(.bold) .font(.system(size:20)) } .background(Image("beige")) .padding() } //notting hill block NavigationLink { //Love_OtherDrugsView() } label: { VStack{ Image("love and other drugs") .resizable() .aspectRatio(contentMode: .fill) .cornerRadius(20) Text("Love & Other Drugs") .fontWeight(.bold) .font(.system(size:20)) } .background(Image("beige")) .padding() } } .scrollContentBackground(.hidden) .background(Image("beige")) Button { showingSavingMovieSheet.toggle() } label: { Image(systemName: "plus.circle.fill") .font(.system(size: 70)) .foregroundColor(.accentColor) .shadow(color: .gray, radius: 0.2, x: 1, y: 1) } .padding() .sheet(isPresented: $showingSavingMovieSheet) { SavingMovieView(vm: SavingMovieViewModel(container: CKContainer.default())) .presentationDetents([.fraction(0.5)]) } } .edgesIgnoringSafeArea(.bottom) .toolbar { ToolbarItem(placement: .principal){ Text("Movies") .font(Font.custom("Titan One",size:50)) .bold() .foregroundColor(Color.accentColor) } } } } } struct MovieView_Previews: PreviewProvider { static var previews: some View { MovieView() } } struct SavingMovieView: View { //making an object from the viewModel @StateObject private var vm: SavingMovieViewModel @State private var title: String = "" @State private var director: String = "" @State private var stars: String = "" @State private var review: String = "" @Environment(\.dismiss) var dismiss init(vm: SavingMovieViewModel){ _vm = StateObject(wrappedValue: vm) } var body: some View { VStack{ Text("Add movie") .bold() .foregroundColor(Color.accentColor) .font(Font.custom("Titan One",size:50)) TextField("Movie Title", text: $title) .textFieldStyle(.roundedBorder) TextField("Director Name", text: $director) .textFieldStyle(.roundedBorder) TextField("Number of rating stars", text: $stars) .textFieldStyle(.roundedBorder) TextField("Description", text: $review) .textFieldStyle(.roundedBorder) Button { vm.saveMovie(title: title, director: director, stars: stars, review: review) dismiss() } label: { Text("Save") } } .padding() } } struct SavingMovieView_Previews: PreviewProvider { static var previews: some View { SavingMovieView(vm: SavingMovieViewModel(container: CKContainer.default())) } }
2
0
459
Aug ’23
Can I access CloudKit's metadata fields with NSPersistentCloudKitContainer?
I've got a simple Core Data Entity that is synchronized with CloudKit via NSPersistentCloudKitContainer. I can read my local fields, but how can I read fields like "Created" & "Modified" from CloudKit? Do I have to add them to my Core Data model and populate them myself? P.S. In his fantastic WWDC talk "Using Core Data with CloudKit", at around 21:40, Nick Gillet talks about how Core Data entities in the CloudKit store are prefixed with "CD_" to separate the things that it manages from the ones CloudKit implements. Then he says: "You wouldn't believe how many people add modify date to their CKRecord". Like it's something redundant.
0
0
409
Aug ’23
cannot push coredata records to cloudkit
coredata pushed schema to cloudkit only for those entities for which I created records. But the record data did not get pushed. I set recordName as Queryable and modifiedTimestamp as both Queryable and sortable. Query does not show the records. I look at Xcode console gives this output for one of the entities that got pushed to cloudkit : CoreData: debug: CoreData+CloudKit: -[PFCloudKitSerializer newCKRecordsFromObject:fullyMaterializeRecords:includeRelationships:error:](575): Serializer has finished creating record: <CKRecord: 0x13f40f920; recordType=CD_Contact, recordID=26809600-B329-4C17-B3E1-6EA5FC177F7C:(com.apple.coredata.cloudkit.zone:__defaultOwner__), values={ "CD_contact" = "26809600-B329-4C17-B3E1-6EA5FC177F7C"; "CD_contactEmail_ckAsset", "CD_contact", "CD_contactEmail", "<CKRecord: 0x13f40f920; recordType=CD_Contact, recordID=26809600-B329-4C17-B3E1-6EA5FC177F7C:(com.apple.coredata.cloudkit.zone:__defaultOwner__), recordChangeTag=5, values={\n \"CD_email\" = Email;\n \"CD_entityName\" = Contact;\n \"CD_firstName\" = V;\n \"CD_imageName\" = \"{ length=20834, sha256=d582bd2ccc7d93138b3a5ad4799443152860268e34f48ace54a0708f3e2f3aba }\";\n \"CD_lastName\" = R;\n \"CD_phone\" = 2;\n \"CD_screenName\" = Vr;\n \"CD_userRating\" = \"*****\";\n \"CD_userType\" = Household;\n}>", Also schema for some other entities that do not have any core data records did not get pushed to CloudKit. I thought the entire coredata schema should get pushed along with the records. Looks like it is pushing those entities that have some records but without pushing data. I reset the cloudkit environment and tried again, but issue is not resolved. Also the AppDelegate never gets called. I thought the line below should have called AppDelegate @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate: AppDelegate Cross referenced persistenceController in AppDelegate. That did not help either Code listed below. Please let me know how to fix the above two issues? main struct GreenApp: App { @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate: AppDelegate static var fcmToken: String? let gcmMessageIDKey = "gcm.Message_ID" let persistenceController = PersistenceController.shared var body: some Scene { WindowGroup { ContentView() .environment(\.managedObjectContext, persistenceController.container.viewContext) } } } 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: "Green") 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. fatalError("Unresolved error \(error), \(error.userInfo)") } }) container.viewContext.automaticallyMergesChangesFromParent = true container.viewContext.mergePolicy = NSMergeByPropertyStoreTrumpMergePolicy // external changes trumping in-memory changes. } } Appdelegate code: class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate, ObservableObject { static var fcmToken: String? let gcmMessageIDKey = "gcm.Message_ID" let persistenceController = PersistenceController.shared func applicationDidFinishLaunching(_ application: UIApplication) { do { // Use the container to initialize the development schema. try persistenceController.container.initializeCloudKitSchema(options: []) } catch { // Handle any errors. fatalError("###\(#function): failed to load persistent stores: \(error)") } if #available(iOS 10.0, *) { // For iOS 10 display notification (sent via APNS) UNUserNotificationCenter.current().delegate = self let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound] UNUserNotificationCenter.current().requestAuthorization(options: authOptions, completionHandler: { granted, error in }) } else { let settings: UIUserNotificationSettings = UIUserNotificationSettings(types:[.alert, .badge, .sound], categories: nil) application.registerUserNotificationSettings(settings) } DispatchQueue.main.async { application.registerForRemoteNotifications() } } }
2
0
652
Aug ’23
SwiftData CloudKit integration requires that all attributes be optional, or have a default value set
After install XCode 15 beta 6: @Model class WordResult { var text = "" var translation:[String] = [] init(){ } } got this error: Variable 'self._$backingData' used before being initialized so I changed to : @Model class WordResult { var text:String var translation:[String] init(){ self.text = "" self.translation = [] } } Then got this: CloudKit integration requires that all attributes be optional, or have a default value set It seems it can not work with cloudkit now.
5
3
1.6k
Aug ’23