iCloud & Data

RSS for tag

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

CloudKit Documentation

Posts under iCloud & Data subtopic

Post

Replies

Boosts

Views

Activity

I'm receiving an Error while trying to modify records created by another appleID in CloudKit Public DataBase.
Both appleIDs(create and modify/save) sign in iCloud. I use the following code to modify and save records: self.containerIdentifier).publicCloudDatabase database.fetch(withRecordID: CKRecord.ID(recordName:groupID), completionHandler: { record, error in if error == nil && record != nil { if let iDs : [String] = record!.object(forKey: "memberIDs") as? Array { if iDs.count < self.maxMemberCount { if let mems: [String] = record!.object(forKey: "memberNames") as? Array { if !(mems as NSArray).contains(name) { var members = mems members.append(name) record!.setObject(members as CKRecordValue, forKey: "memberNames") var iDs : [String] = record!.object(forKey: "memberIDs") as! Array iDs.append(self.myMemberID) record!.setObject(iDs as CKRecordValue, forKey:"memberIDs") database.save(record!, completionHandler: { record, error in if error == nil { } else { completion(error as NSError?) dPrint("Error : \(String(describing: error))") } }) }else{ let DBError : NSError = NSError(domain: "DBError", code: 89, userInfo: ["localizedDescription": NSLocalizedString("Your nickname already used.", comment:"")]) completion(DBError) print("change your nickname") } }else{ print("group DB error") let DBError : NSError = NSError(domain: "DBError", code: 88, userInfo: ["localizedDescription": NSLocalizedString("Please try later.", comment:"")]) completion(DBError) } } }else{ print("Error : \(String(describing: error))") } }) I received the following error message: ?Error saving records: <CKError 0x600000bbe970: "Service Unavailable" (6/NSCocoaErrorDomain:4099); "Error connecting to CloudKit daemon. This could happen for many reasons, for example a daemon exit, a device reboot, a race with the connection inactivity monitor, invalid entitlements, and more. Check the logs around this time to investigate the cause of this error."; Retry after 5.0 seconds> baseNSError@0 NSError domain: "CKErrorDomain" - code: 6 _userInfo __NSDictionaryI * 4 key/value pairs 0x000060000349e300 [0] (null) "NSLocalizedDescription" : "Error connecting to CloudKit daemon. This could happen for many reasons, for example a daemon exit, a device reboot, a race with the connection inactivity monitor, invalid entitlements, and more. Check the logs around this time to investigate the cause of this error." key __NSCFConstantString * "NSLocalizedDescription" 0x00000001117155a0 value __NSCFConstantString * "Error connecting to CloudKit daemon. This could happen for many reasons, for example a daemon exit, a device reboot, a race with the connection inactivity monitor, invalid entitlements, and more. Check the logs around this time to investigate the cause of this error." 0x000000011057e700 [1] (null) "CKRetryAfter" : Int32(5) key __NSCFConstantString * "CKRetryAfter" 0x000000011057c680 value NSConstantIntegerNumber? Int32(5) 0x00000001105c2ed0 [2] (null) "CKErrorDescription" : "Error connecting to CloudKit daemon. This could happen for many reasons, for example a daemon exit, a device reboot, a race with the connection inactivity monitor, invalid entitlements, and more. Check the logs around this time to investigate the cause of this error." key __NSCFConstantString * "CKErrorDescription" 0x0000000110568d00 value __NSCFConstantString * "Error connecting to CloudKit daemon. This could happen for many reasons, for example a daemon exit, a device reboot, a race with the connection inactivity monitor, invalid entitlements, and more. Check the logs around this time to investigate the cause of this error." 0x000000011057e700 [3] (null) "NSUnderlyingError" : domain: "NSCocoaErrorDomain" - code: 4099 key __NSCFConstantString * "NSUnderlyingError" 0x0000000111715540 value NSError? domain: "NSCocoaErrorDomain" - code: 4099 0x00006000016cc300
0
0
334
Nov ’24
Crash with NSAttributedString in Core Data
I am trying out the new AttributedString binding with SwiftUI’s TextEditor in iOS26. I need to save this to a Core Data database. Core Data has no AttributedString type, so I set the type of the field to “Transformable”, give it a custom class of NSAttributedString, and set the transformer to NSSecureUnarchiveFromData When I try to save, I first convert the Swift AttributedString to NSAttributedString, and then save the context. Unfortunately I get this error when saving the context, and the save isn't persisted: CoreData: error: SQLCore dispatchRequest: exception handling request: <NSSQLSaveChangesRequestContext: 0x600003721140> , <shared NSSecureUnarchiveFromData transformer> threw while encoding a value. with userInfo of (null) Here's the code that tries to save the attributed string: struct AttributedDetailView: View { @ObservedObject var item: Item @State private var notesText = AttributedString() var body: some View { VStack { TextEditor(text: $notesText) .padding() .onChange(of: notesText) { item.attributedString = NSAttributedString(notesText) } } .onAppear { if let nsattributed = item.attributedString { notesText = AttributedString(nsattributed) } else { notesText = "" } } .task { item.attributedString = NSAttributedString(notesText) do { try item.managedObjectContext?.save() } catch { print("core data save error = \(error)") } } } } This is the attribute setup in the Core Data model editor: Is there a workaround for this? I filed FB17943846 if someone can take a look. Thanks.
2
0
169
Jun ’25
SQLLite 3 and iOS 18
Hi, I've got an app using SQLLite. Under iOS 17 I could insert and select rows with no issues. Under iOS 18 the same code runs without errors but the select returns no results. Various select statements with and without where clause's, and freshly created database files all behave the same way. Unless... the phone is in developer mode, then it works same as iOS 17. I'm assuming it's some security change, how do we fix it? Same issue with Swift 5 and Swift 6 for context but I don't think its related to Swift. Thanks !
5
0
336
Oct ’24
NSFetchedResultsController index out of bounds during context merging changes
I've noticed several crashes that look like they're caused by an index out of bound in internal methods of NSFetchedResultsController. This happens while changes are merged from the persistent store container into the view context. Here's an example of the last exception backtrace. Exactly which internal methods that are called in - [NSFetchedResultsController(PrivateMethods) _core_managedObjectContextDidChange:] vary between crash reports but they all end up crashing from _NSArrayRaiseBoundException. The Core Data stack consists of one persistent store, one persistent store coordinator that the view context is set up to automatically merge changes from, and data is saved to disk from background context. persistentContainer.loadPersistentStores(...) viewContext = persistentContainer.viewContext viewContext.automaticallyMergesChangesFromParent = true backgroundContext = persistentContainer.newBackgroundContext() backgroundContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy backgroundClientContext = persistentContainer.newBackgroundContext() backgroundClientContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy Does anyone have any ideas what could be causing this? Thankful for any ideas or advice on how to investigate further.
2
0
707
Jan ’25
Strange behavior with 100k+ records in NSPersistentCloudKitContainer
I have been using the basic NSPersistentContainer with 100k+ records for a while now with no issues. The database size can fluctuate a bit but on average it takes up about 22mb on device. When I switch the container to NSPersistentCloudKitContainer, I see a massive increase in size to ~150mb initially. As the sync engine uploads records to iCloud it has ballooned to over 600mb on device. On top of that, the user's iCloud usage in settings reports that it takes up 1.7gb in the cloud. I understand new tables are added and history tracking is enabled but the size increase seems a bit drastic. I'm not sure how we got from 22mb to 1.7gb with the exact same data. A few other things that are important to note: I import all the 100k+ records at once when testing the different containers. At the time of the initial import there is only 1 relation (an import group record) that all the records are attached to. I save the background context only once after all the records and the import group have been made and added to the context. After the initial import, some of these records may have a few new relations added to them over time. I suppose this could be causing some of the size increase, but its only about 20,000 records that are updated. None of the records include files/ large binary data. Most of the attributes are encrypted. I'm syncing to the dev iCloud environment. When I do make a change to a single attribute in a record, CloudKit reports that every attribute has been modified (not sure if this is normal or not ) Also, When syncing to a new device, the sync can take hours - days. I'm guessing it's having to sync both the new records and the changes, but it exponentially gets slower as more records are downloaded. The console will show syncing activity, but new records are being added at a slower rate as more records are added. After about 50k records, it grinds to a halt and while the console still shows sync activity, only about 100 records are added every hour. All this to say i'm very confused where these issues are coming from. I'm sure its a combination of how i've setup my code and the vast record count, record history, etc. If anyone has any ideas it would be much appreciated.
2
0
577
Nov ’24
Is it possible to use an additional local ModelContainer in a document based SwiftData app?
I have a document based SwiftData app in which I would like to implement a persistent cache. For obvious reasons, I would not like to store the contents of the cache in the documents themselves, but in my app's data directory. Is a use case, in which a document based SwiftData app uses not only the ModelContainers from the currently open files, but also a ModelContainer writing a database file in the app's documents directory (for cache, settings, etc.) supported? If yes, how can you inject two different ModelContexts, one tied to the currently open file and one tied to the local database, into a SwiftUI view?
0
0
45
Apr ’25
Core Data transformable vs relationship
I'm working on an app that is using Core Data. I have a custom big number class that boils down to a double and an integer, plus math functions. I've been using transformable types to store these big numbers, but its forcing me to do a lot of ugly casts since the number class is used throughout the application. I figure I can either have my stored values be named differently (e.g. prefix with underscore) and have a computed variable to cast it to the correct type, or find some way to move the big number class to being an NSManagedObject. The issue with this is that the inverse relationships would be massive for the big number class, since multiple entities use the class in multiple properties already. Would it be recommended that I just keep using Transformable types and casts to handle this, or is there some standard way to handle a case like this in Core Data relationships?
0
0
321
Oct ’24
SwiftData data crashes with @Relationship
I've noticed that SwiftData's @Relationship seems to potentially cause application crashes. The crash error is shown in the image. Since this crash appears to be random and I cannot reproduce it under specific circumstances, I can only temporarily highlight that this issue seems to exist. @Model final class TrainInfo { @Relationship(deleteRule: .cascade, inverse: \StopStation.trainInfo) var stations: [StopStation]? } @Model final class StopStation { @Relationship var trainInfo: TrainInfo? } /// some View var origin: StopStationDisplayable? { if let train = train as? TrainInfo { return train.stations?.first(where: { $0.isOrigin }) ?? train.stations?.first(where: { $0.isStarting }) } return nil } // Some other function or property func someFunction() { if let origin, let destination { // Function implementation } }
1
0
82
Apr ’25
SwiftData - disable Persistent History Tracking
Hello, I am building a pretty large database (~40MB) to be used in my SwiftData iOS app as read-only. While inserting and updating the data, I noticed a substantial increase in size (+ ~10MB). A little digging pointed to ACHANGE and ATRANSACTION tables that apparently are dealing with Persistent History Tracking. While I do appreciate the benefits of that, I prefer to save space. Could you please point me in the right direction?
0
0
62
Apr ’25
Object deleted in MOC not properly deleted in child MOC
I have two contexts, MAIN and VIEW. I construct an object in MAIN and it appears in VIEW (which I use to display it in the UI). Then I delete the object in MAIN. Because the UI holds a reference to the object in VIEW, VIEW records it as a pending delete (Problem 1). I don't understand why it does this nor can I find this behaviour documented. Docs for deletedObjects say "objects that will be removed from their persistent store during the next save". This has already happened! (Problem 2) Then I rollback the VIEW context, and the object is resurrected. awakeFromInsert is called again. While the object (correctly) does not appear in a freshly executed fetch request, it does appear in the @FetchRequest of the SwiftUI View which is now displaying stale data. I cannot figure out how to get SwiftUI to execute the fetch request again (I know I can force regeneration of the UI, but would like to avoid this). This is self-contained demonstration of the problem that can be run in a Playground. Press Create, then Delete (note console output), then Rollback (note console output, and that element count changes from 0 to 1 in the UI) import CoreData import SwiftUI @objc(TestEntity) class TestEntity : NSManagedObject, Identifiable{ @NSManaged var id : UUID? override func awakeFromInsert() { print("Awake from insert") if id == nil { // Avoid resetting ID when we resurrect the phantom delete self.id = UUID() } super.awakeFromInsert() } class func add(in context: NSManagedObjectContext) -> UUID { let id = UUID() context.performAndWait { let mo = TestEntity(context: context) mo.id = id } return id } class func fetch(in context: NSManagedObjectContext) -> [TestEntity] { let fr = TestEntity.fetchRequest() return try! context.fetch(fr) as! [TestEntity] } } class CoreDataStack { // Main is attached to the store var main : NSManagedObjectContext! // View is a child context of main and used to display the UI var view : NSManagedObjectContext! // Set up a simple entity with an ID attribute func getEntities() -> [NSEntityDescription] { let testEntity = NSEntityDescription() testEntity.managedObjectClassName = "TestEntity" testEntity.name = "TestEntity" let idAttribute = NSAttributeDescription() idAttribute.name = "id" idAttribute.type = .uuid testEntity.properties.append(idAttribute) return [testEntity] } init() { let model = NSManagedObjectModel() model.entities = getEntities() let container = NSPersistentContainer(name: "TestModel", managedObjectModel: model) let description = NSPersistentStoreDescription() description.type = NSInMemoryStoreType container.persistentStoreDescriptions = [description] container.loadPersistentStores { desc, error in if error != nil { fatalError("Failed to set up coredata") } } main = container.viewContext view = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) view.automaticallyMergesChangesFromParent = true view.parent = main } func create() { let entityId = TestEntity.add(in: main) main.performAndWait { try! main.save() } } func delete() { main.performAndWait { if let mo = TestEntity.fetch(in: main).first { main.delete(mo) try! main.save() } } self.view.perform { // We only find that we have a pending delete here if we hold a reference to the object, e.g. in the UI via @FetchRequest if(self.view.deletedObjects.count != 0) { print("!!! view has a pending delete, even though main has saved the delete !!!") } } } func rollback() { self.view.perform { self.view.rollback() // PROBLEM We now have a resurrected object. Note that awakeFromInsert // was called again. } } } import SwiftUI import PlaygroundSupport let stack = CoreDataStack() struct ContentView: View { @FetchRequest(sortDescriptors: []) private var entities: FetchedResults<TestEntity> @State var renderID = UUID() var body: some View { VStack { Text("\(entities.count) elements") Button("Create") { stack.create() } Button("Delete") { stack.delete() } Button("Rollback") { stack.rollback() // PROBLEM After rollback we get the element displaying in // the UI again, even though it isn't present in a freshly // executed fetch request. // The @FetchRequest is picking up the resurrected TestEntity in view // But not actually issuing a fetch. self.renderID = UUID() entities.nsPredicate } }.id(renderID) } } //stack.execute() let view = ContentView() .environment(\.managedObjectContext, stack.view) PlaygroundPage.current.setLiveView(view)
4
0
950
Oct ’24
Inquiry Regarding Data Migration Using Quick Start
I am currently developing an iOS app with a new feature that utilizes Quick Start for data migration between devices. We are testing this in a test environment using an app distributed via TestFlight. However, we are encountering an issue where the app installed on the pre-migration device (distributed via TestFlight) does not transfer to the post-migration device. Could this issue be related to the fact that the app was distributed via TestFlight? Is there any restriction where only apps released via the App Store can be migrated using Quick Start? We would appreciate it if you could provide some insights into the cause of this issue and any alternative testing methods.
1
0
563
Oct ’24
iCloud Mail being rejected by Barracuda Email Protection due to missing PTR record.
My client is using iCloud Mail with his custom domain and he communicated with many govt organizations which seem to all be using Barracuda Email Protection for their spam prevention. I have properly configured his SPF, DKIM & DMARC DNS records however his emails were still being rejected. (Email header below) I contacted Barracuda support with the email header and they replied saying that the emails were rejected becuase Apple Mail has missing PTR records. I have sent dozens of emails for testing and looking at all their headers I can see (ms-asmtp-me-k8s.p00.prod.me.com [17.57.154.37]) which does not have a PTR record. ----FULL EMAIL HEADER WITH 3RD PARTY DOMAINS REMOVED----- <recipient_email_address>: host d329469a.ess.barracudanetworks.com[209.222.82.255] said: 550 permanent failure for one or more recipients (recipient_email_address:blocked) (in reply to end of DATA command) Reporting-MTA: dns; p00-icloudmta-asmtp-us-west-3a-100-percent-10.p00-icloudmta-asmtp-vip.icloud-mail-production.svc.kube.us-west-3a.k8s.cloud.apple.com X-Postfix-Queue-ID: 8979C18013F8 X-Postfix-Sender: rfc822; sender_email_address Arrival-Date: Thu, 20 Mar 2025 12:30:05 +0000 (UTC) Final-Recipient: rfc822; @****** Original-Recipient: rfc822;recipient_email_address Action: failed Status: 5.0.0 Remote-MTA: dns; d329469a.ess.barracudanetworks.com Diagnostic-Code: smtp; 550 permanent failure for one or more recipients (recipient_email_address:blocked) Return-Path: <sender_email_address> DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=sender_domain; s=sig1; bh=CyUt/U7mIHwXB5OQctPjRH/OxLH7GsLR54JjGuRkj9Y=; h=From:Message-Id:Content-Type:Mime-Version:Subject:Date:To:x-icloud-hme; b=hwEbggsctiCRlMlEgovBTjB/0sPRCb2k+1wzHRZ2dZNrZdOqvFSNWU+Aki9Bl8nfv eEOoXz5qWxO2b2rEBl08lmRQ3hCyroayIn4keBRrgkxL1uu4zMTaDUHyau2vVnzC3h ZmwQtQxiu7QvTS/Sp8jjJ/niOPSzlfhphqMxnQAZi/jmJGcZPadT8K+7+PhRllVnI+ TElJarN1ORQu+CaPGhEs9/F7AIcjJNemnVg1cude7EUuO9va8ou49oFExWTLt7YSMl s+88hxxGu3GugD3eBnitzVo7s7/O9qkIbDUjk3w04/p/VOJ+35Mvi+v/zB9brpYwC1 B4dZP+AhwJDYA== Received: from smtpclient.apple (ms-asmtp-me-k8s.p00.prod.me.com [17.57.154.37]) by p00-icloudmta-asmtp-us-west-3a-100-percent-10.p00-icloudmta-asmtp-vip.icloud-mail-production.svc.kube.us-west-3a.k8s.cloud.apple.com (Postfix) with ESMTPSA id 8979C18013F8; Thu, 20 Mar 2025 12:30:05 +0000 (UTC) From: Marcel Brunel <sender_email_address> Message-Id: <2E8D69EA-FCA6-4F5D-9D42-22A955C073F6@sender_domain> Content-Type: multipart/alternative; boundary="Apple-Mail=_F9AC7D29-8520-4B25-9362-950CB20ADEC5" Mime-Version: 1.0 (Mac OS X Mail 16.0 (3826.400.131.1.6)) Subject: Re: [EXTERNAL] - Re: Brunel - 2024 taxes Date: Thu, 20 Mar 2025 07:29:27 -0500 In-Reply-To: <SA0PR18MB350300DE7274C018F66EEA24F2D82@SA0PR18MB3503_namprd18_prod_outlook_com> To: Troy Womack <recipient_email_address> References: <SA0PR18MB350314D0B88E283C5C8E1BB6F2DE2@SA0PR18MB3503_namprd18_prod_outlook_com> <9B337A3E-D373-48C5-816F-C1884BDA6F42@sender_domain> <SA0PR18MB350341A7172E8632D018A910F2D82@SA0PR18MB3503_namprd18_prod_outlook_com> <SA0PR18MB350300DE7274C018F66EEA24F2D82@SA0PR18MB3503_namprd18_prod_outlook_com> X-Mailer: Apple Mail (2.3826.400.131.1.6) X-Proofpoint-ORIG-GUID: uqebp2OIbPqBr3dYsAxdFVkCNbM5Cxyl X-Proofpoint-GUID: uqebp2OIbPqBr3dYsAxdFVkCNbM5Cxyl X-Proofpoint-Virus-Version: vendor=baseguard engine=ICAP:2.0.293,Aquarius:18.0.1093,Hydra:6.0.680,FMLib:17.12.68.34 definitions=2025-03-20_03,2025-03-19_01,2024-11-22_01 X-Proofpoint-Spam-Details: rule=notspam policy=default score=0 bulkscore=0 clxscore=1030 suspectscore=0 mlxlogscore=999 mlxscore=0 phishscore=0 malwarescore=0 spamscore=0 adultscore=0 classifier=spam adjust=0 reason=mlx scancount=1 engine=8.19.0-2411120000 definitions=main-2503200077
0
0
139
Mar ’25
CloudKit Integration Issue: Record Type Not Found
Hello everyone, I'm working on an iOS app that uses CloudKit for data synchronization. I'm encountering an issue where my app can't find the "JournalPrompt" record type in the public database. Here's the relevant code and error messages (I'm using placeholders like [APP_NAME] or [CONTAINER_IDENTIFIER]): private func fetchPromptsFromiCloud() { let container = CKContainer(identifier: "[CONTAINER_IDENTIFIER]") let publicDatabase = container.publicCloudDatabase // Create a predicate to query for the specific record let predicate = NSPredicate(format: "recordID.recordName == %@", "B6663053-FC2E-4645-938B-9FA528D59663") let query = CKQuery(recordType: "JournalPrompt", predicate: predicate) publicDatabase.perform(query, inZoneWith: nil) { [weak self] (records, error) in if let error = error as? CKError { if error.code == .unknownItem { print("JournalPrompt record type does not exist or the specific record was not found in the public database.") } else { print("Error fetching record from iCloud public database: \(error)") } return } guard let record = records?.first else { print("No record found with the specified ID in the public database.") return } print("Found record in public database:") print("Record ID: \(record.recordID.recordName)") print("Text: \(record["text"] as? String ?? "No text")") print("Creation Date: \(record.creationDate ?? Date())") print("Used Count: \(record["usedCount"] as? Int ?? 0)") print("Is Default: \(record["isDefault"] as? Bool ?? false)") } } Error When I run this code, I get the following error: Error fetching record from iCloud public database: <CKError 0x600000c072a0: "Invalid Arguments" (12/1009); "Invalid predicate: recordKey (recordID.recordName) contains invalid characters"> I've also implemented a function to check the CloudKit schema: func checkCloudKitSchema() { checkDatabase(scope: .private) checkDatabase(scope: .public) } private func checkDatabase(scope: CKDatabase.Scope) { let container = CKContainer(identifier: "[CONTAINER_IDENTIFIER]") let database = scope == .private ? container.privateCloudDatabase : container.publicCloudDatabase print("Checking \(scope == .private ? "private" : "public") database") database.fetchAllRecordZones { (zones, error) in if let error = error { print("Error fetching record zones: \(error)") return } print("Available record zones in \(scope == .private ? "private" : "public") database:") zones?.forEach { zone in print("- \(zone.zoneID.zoneName)") } let query = CKQuery(recordType: "JournalPrompt", predicate: NSPredicate(value: true)) database.perform(query, inZoneWith: nil) { (records, error) in if let error = error as? CKError, error.code == .unknownItem { print("JournalPrompt record type does not exist in the \(scope == .private ? "private" : "public") database.") } else if let error = error { print("Error fetching records from \(scope == .private ? "private" : "public") database: \(error)") } else if let records = records, !records.isEmpty { print("JournalPrompt record type exists in the \(scope == .private ? "private" : "public") database.") print("Fetched \(records.count) JournalPrompt records:") for record in records { print("Record ID: \(record.recordID.recordName)") print("Fields:") record.allKeys().forEach { key in print(" - \(key): \(type(of: record[key]))") } print("---") } } else { print("JournalPrompt record type exists in the \(scope == .private ? "private" : "public") database, but no records found.") } } } } When I run this, I get: Checking public database Available record zones in public database: _defaultZone JournalPrompt record type does not exist in the public database. CloudKit Database Setup I've set up my CloudKit Database as follows: And my data model is as follows: Despite this setup, my app can't seem to find or interact with the JournalPrompt record type. I've double-checked that my app's identifier matches the one in the CloudKit dashboard, and I've verified that the record type name is spelled correctly. Questions: Why might my app be unable to find the JournalPrompt record type, even though it's defined in the CloudKit dashboard? Is there anything wrong with my query or error handling that could be causing this issue? Are there any common pitfalls or setup steps I might have missed when integrating CloudKit? Any insights or suggestions would be greatly appreciated. I really appreciate any help you can provide.
2
0
717
Sep ’24
SwiftData duplicates values inside array on insert()
After copying and inserting instances I am getting strange duplicate values in arrays before saving. My models: @Model class Car: Identifiable { @Attribute(.unique) var name: String var carData: CarData func copy() -> Car { Car( name: "temporaryNewName", carData: carData ) } } @Model class CarData: Identifiable { var id: UUID = UUID() var featuresA: [Feature] var featuresB: [Feature] func copy() -> CarData { CarData( id: UUID(), featuresA: featuresA, featuresB: featuresB ) } } @Model class Feature: Identifiable { @Attribute(.unique) var id: Int @Attribute(.unique) var name: String @Relationship( deleteRule:.cascade, inverse: \CarData.featuresA ) private(set) var carDatasA: [CarData]? @Relationship( deleteRule:.cascade, inverse: \CarData.featuresB ) private(set) var carDatasB: [CarData]? } The Car instances are created and saved to SwiftData, after that in code: var fetchDescriptor = FetchDescriptor<Car>( predicate: #Predicate<Car> { car in car.name == name } ) let cars = try! modelContext.fetch( fetchDescriptor ) let car = cars.first! print("car featuresA:", car.featuresA.map{$0.name}) //prints ["green"] - expected let newCar = car.copy() newCar.name = "Another car" newcar.carData = car.carData.copy() print("newCar featuresA:", newCar.featuresA.map{$0.name}) //prints ["green"] - expected modelContext.insert(newCar) print("newCar featuresA:", newCar.featuresA.map{$0.name}) //prints ["green", "green"] - UNEXPECTED! /*some code planned here modifying newCar.featuresA, but they are wrong here causing issues, for example finding first expected green value and removing it will still keep the unexpected duplicate (unless iterating over all arrays to delete all unexpected duplicates - not optimal and sloooooow).*/ try! modelContext.save() print("newCar featuresA:", newCar.featuresA.map{$0.name}) //prints ["green"] - self-auto-healed??? Tested on iOS 18.2 simulator and iOS 18.3.1 device. Minimum deployment target: iOS 17.4 The business logic is that new instances need to be created by copying and modifying previously created ones, but I would like to avoid saving before all instances are created, because saving after creating each instance separately takes too much time overall. (In real life scenario there are more than 10K objects with much more properties, updating just ~10 instances with saving takes around 1 minute on iPhone 16 Pro.) Is this a bug, or how can I modify the code (without workarounds like deleting duplicate values) to not get duplicate values between insert() and save()?
8
0
333
Mar ’25
CoreData/Database question
I am working on an app that will have about 200mb of data in a database. I would like to install a json file with 3-4 mb on the phone with the app, and then be able to send small packets of information to the user of the app as they are using the app, for example if they hit a button with a link to an instagram page, I can have the database/server send the link to the app, it will be just small bits of information going from the database to the phone, and perhaps I would do some location tracking and getting some information from the user to build up personal preferences etc. I'm wondering if coredata would be the best way to get smaller packets of information to the phone quickly or if I should think about firebase or something else. I was interested in using Cloudkit, but it seems like Cloudkit is really more about syncing devices and for getting information from the user to the database. It's been really hard to find any information about the strengths versus weaknesses of different databases and how they interact with mobile apps.
0
0
299
Oct ’24
Schema Migrations with CloudKit Not Working
I have not had any successful Schema Migration with CloudKit so far so I'm trying to do with with just very basic attributes, with multiple Versioned Schemas This is the code in my App Main var sharedModelContainer: ModelContainer = { let schema = Schema(versionedSchema: AppSchemaV4.self) do { return try ModelContainer( for: schema, migrationPlan: AppMigrationPlan.self, configurations: ModelConfiguration(cloudKitDatabase: .automatic)) } catch { fatalError("Could not create ModelContainer: \(error)") } }() var body: some Scene { WindowGroup { ItemListView() } .modelContainer(sharedModelContainer) } And this is the code for my MigrationPlan and VersionedSchemas. typealias Item = AppSchemaV4.Item3 enum AppMigrationPlan: SchemaMigrationPlan { static var schemas: [any VersionedSchema.Type] { [AppSchemaV1.self, AppSchemaV2.self, AppSchemaV3.self, AppSchemaV4.self] } static var stages: [MigrationStage] { [migrateV1toV2, migrateV2toV3, migrateV3toV4] } static let migrateV1toV2 = MigrationStage.lightweight( fromVersion: AppSchemaV1.self, toVersion: AppSchemaV2.self ) static let migrateV2toV3 = MigrationStage.lightweight( fromVersion: AppSchemaV2.self, toVersion: AppSchemaV3.self ) static let migrateV3toV4 = MigrationStage.custom( fromVersion: AppSchemaV3.self, toVersion: AppSchemaV4.self, willMigrate: nil, didMigrate: { context in // Fetch all Item1 instances let item1Descriptor = FetchDescriptor<AppSchemaV3.Item1>() let items1 = try context.fetch(item1Descriptor) // Fetch all Item2 instances let item2Descriptor = FetchDescriptor<AppSchemaV3.Item2>() let items2 = try context.fetch(item2Descriptor) // Convert Item1 to Item3 for item in items1 { let newItem = AppSchemaV4.Item3(name: item.name, text: "Migrated from Item1 on \(item.date)") context.insert(newItem) } // Convert Item2 to Item3 for item in items2 { let newItem = AppSchemaV4.Item3(name: item.name, text: "Migrated from Item2 with value \(item.value)") context.insert(newItem) } try? context.save() } ) } enum AppSchemaV1: VersionedSchema { static var versionIdentifier: Schema.Version = Schema.Version(1, 0, 0) static var models: [any PersistentModel.Type] { [Item1.self] } @Model class Item1 { var name: String = "" init(name: String) { self.name = name } } } enum AppSchemaV2: VersionedSchema { static var versionIdentifier: Schema.Version = Schema.Version(2, 0, 0) static var models: [any PersistentModel.Type] { [Item1.self] } @Model class Item1 { var name: String = "" var date: Date = Date() init(name: String) { self.name = name self.date = Date() } } } enum AppSchemaV3: VersionedSchema { static var versionIdentifier: Schema.Version = Schema.Version(3, 0, 0) static var models: [any PersistentModel.Type] { [Item1.self, Item2.self] } @Model class Item1 { var name: String = "" var date: Date = Date() init(name: String) { self.name = name self.date = Date() } } @Model class Item2 { var name: String = "" var value: Int = 0 init(name: String, value: Int) { self.name = name self.value = value } } } enum AppSchemaV4: VersionedSchema { static var versionIdentifier: Schema.Version = Schema.Version(4, 0, 0) static var models: [any PersistentModel.Type] { [Item1.self, Item2.self, Item3.self] } @Model class Item1 { var name: String = "" var date: Date = Date() init(name: String) { self.name = name self.date = Date() } } @Model class Item2 { var name: String = "" var value: Int = 0 init(name: String, value: Int) { self.name = name self.value = value } } @Model class Item3 { var name: String = "" var text: String = "" init(name: String, text: String) { self.name = name self.text = text } } } My experiment was: To create Items for every version of the schema Updating the typealias along the way to reflect the latest Item version. Updating the Schema in my ModelContainer to reflect the latest Schema Version. By AppSchemaV4, I have expected all my Items to be displayed/migrated to Item3, but it does not seem to be the case. I can only see newly created Item3 records. My question is, is there something wrong with how I'm doing the migrations? or are migrations not really working with CloudKit right now?
1
0
372
Mar ’25
SwiftData and async functions
Hello, I recently published an app that uses Swift Data as its primary data storage. The app uses concurrency, background threads, async await, and BLE communication. Sadly, I see my app incurs many fringe crashes, involving EXC_BAD_ACCESS, KERN_INVALID_ADDRESS, EXC_BREAKPOINT, etc. I followed these guidelines: One ModelContainer that is stored as a global variable and used throughout. ModelContexts are created separately for each task, changes are saved manually, and models are not passed around. Threads with different ModelContexts might manipulate and/or read the same data simultaneously. I was under the impression this meets the usage requirements. I suspect perhaps the issue lies in my usage of contexts in a single await function, that might be paused and resumed on a different thread (although same execution path). Is that the case? If so, how should SwiftData be used in async scopes? Is there anything else particularly wrong in my approach?
4
0
1.2k
Mar ’25
Records or Fields are Missing or Corrupt in Users Private CloudKit Databases (Recent Changes to CloudKit?)
Hi all, I've contacted Apple about this privately but I wanted to post this publicly too just to see if anyone else is experiencing the same issue. We use CloudKit to store "documents" (we'll call them) for our users. We use it directly, not via CoreData etc but through the lower level APIs. This has been working great for the last 9 months or so. Since a few days ago we've started receiving reports from users that their data has disappeared without a trace from their app. Obviously this is very serious and severe for us. We keep a local copy of the users data but if CloudKit tells us this data has been deleted we remove that local copy to keep in sync. Nothing has changed client side in terms of our code, and the only way we can see that could cause this, is a fetch that we perform asking for a list of the users "documents" is returning no rows/results, or possibly returning rows with invalid or missing fields. We have about 30,000 active users per day (1.5m requests/day) using CloudKit and we have only a handful of reports of this. Again this only started happening this week after 9 months of good service. Has anyone else noticed anything "strange" lately, fetches returning empty? fields missing? Is anyone at Apple aware of any recent changes to CloudKit? or outages? We're really unsure how or who should handle this and who we can escalate to? Any help appreciated. We have a workaround/mitigation on the way through review at the moment but this is a really big problem for us if we can't rely on CloudKit to remember users data reliably.
1
0
589
Feb ’25