iCloud & Data

RSS for tag

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

CloudKit Documentation

Post

Replies

Boosts

Views

Activity

SwiftData migration error
Distributor ID: com.apple.AppStore Hardware Model: iPhone15,3 Process: DeadLineTodo [5556] Path: /private/var/containers/Bundle/Application/348CC8D5-05FD-41DF-93A3-C15562EF4AA8/DeadLineTodo.app/DeadLineTodo Identifier: andy.DeadLineTodo Version: 2.4.0 (3) AppStoreTools: 15F31e AppVariant: 1:iPhone15,3:17 Code Type: ARM-64 (Native) Role: Foreground Parent Process: launchd [1] Coalition: andy.DeadLineTodo [2089] Date/Time: 2024-06-08 19:13:53.6259 +0800 Launch Time: 2024-06-08 19:13:53.2839 +0800 OS Version: iPhone OS 17.5.1 (21F90) Release Type: User Baseband Version: 2.60.02 Report Version: 104 Exception Type: EXC_BREAKPOINT (SIGTRAP) Exception Codes: 0x0000000000000001, 0x0000000195a2d8c0 Termination Reason: SIGNAL 5 Trace/BPT trap: 5 Terminating Process: exc handler [5556] Triggered by Thread: 0 Thread 0 name: Thread 0 Crashed: 0 libswiftCore.dylib 0x0000000195a2d8c0 _assertionFailure(_:_:file:line:flags:) + 264 (AssertCommon.swift:144) 1 DeadLineTodo 0x0000000100dde700 DeadLineTodoApp.init() + 1140 (DeadLineTodoApp.swift:46) 2 DeadLineTodo 0x0000000100ddef30 protocol witness for App.init() in conformance DeadLineTodoApp + 28 (<compiler-generated>:0) 3 SwiftUI 0x000000019b2c84c0 static App.main() + 116 (App.swift:114) 4 DeadLineTodo 0x0000000100ddeec4 static DeadLineTodoApp.$main() + 40 (<compiler-generated>:0) 5 DeadLineTodo 0x0000000100ddef5c main + 12 (DeadLineTodoApp.swift:32) 6 dyld 0x00000001ba7d1e4c start + 2240 (dyldMain.cpp:1298) Thread 1: 0 libsystem_pthread.dylib 0x00000001f3fa40c4 start_wqthread + 0 (:-1) Thread 2: 0 libsystem_pthread.dylib 0x00000001f3fa40c4 start_wqthread + 0 (:-1) Thread 0 crashed with ARM Thread State (64-bit): x0: 0x8000000100f01ad0 x1: 0x0000000000000000 x2: 0x0000000000000000 x3: 0x00000003019e9bc0 x4: 0x0000000000000000 x5: 0x000000016f16f3e0 x6: 0x000000000000002e x7: 0x0000000000000000 x8: 0x0000000000000100 x9: 0x00000000000000ff x10: 0x0000000000001b80 x11: 0x00000000f3444870 x12: 0x00000000000007fb x13: 0x00000000000007fd x14: 0x00000000f364506f x15: 0x000000000000006f x16: 0x00000000f3444870 x17: 0x0000000000045000 x18: 0x0000000000000000 x19: 0x0000000100f01dba x20: 0x8000000100f01ad0 x21: 0x0000000000000000 x22: 0x000000000000000b x23: 0x0000000000000022 x24: 0x000000000000002e x25: 0x0000000100f01ac0 x26: 0xd000000000000025 x27: 0x0000000000000000 x28: 0x0000000000000000 fp: 0x000000016f16f5c0 lr: 0x0000000195a2d8c0 sp: 0x000000016f16f4f0 pc: 0x0000000195a2d8c0 cpsr: 0x60001000 esr: 0xf2000001 (Breakpoint) brk 1 Binary Images: 0x100c90000 - 0x100f0ffff DeadLineTodo arm64 <c16650393d4537299a08b798b8227d31> /private/var/containers/Bundle/Application/348CC8D5-05FD-41DF-93A3-C15562EF4AA8/DeadLineTodo.app/DeadLineTodo 0x101214000 - 0x10121ffff libobjc-trampolines.dylib arm64e <2e2c05f8377a30899ad91926d284dd03> /private/preboot/Cryptexes/OS/usr/lib/libobjc-trampolines.dylib 0x1959f4000 - 0x195f43fff libswiftCore.dylib arm64e <d9ad5cc1ca2c3f0a8091652b0df56d14> /usr/lib/swift/libswiftCore.dylib 0x19af1c000 - 0x19ccbafff SwiftUI arm64e <c1325fda9da239d2ab83a338b4d8a884> /System/Library/Frameworks/SwiftUI.framework/SwiftUI 0x1ba795000 - 0x1ba821ef7 dyld arm64e <71846eacee653697bf7d790b6a07dcdb> /usr/lib/dyld 0x1f3fa3000 - 0x1f3fafff3 libsystem_pthread.dylib arm64e <1196b6c3333d3450818ff3663484b8eb> /usr/lib/system/libsystem_pthread.dylib EOF DeadLineTodoApp.swift import SwiftData typealias TodoData = TodoDataSchemaV8.TodoData typealias UserSetting = TodoDataSchemaV8.UserSetting enum TodoDataMigrationPlan: SchemaMigrationPlan { static var schemas: [VersionedSchema.Type] { [TodoDataSchemaV1.self, TodoDataSchemaV2.self, TodoDataSchemaV3.self, TodoDataSchemaV4.self, TodoDataSchemaV5.self, TodoDataSchemaV6.self, TodoDataSchemaV7.self, TodoDataSchemaV8.self] } static var stages: [MigrationStage]{ [migrationV1toV2, migrationV2toV3, migrationV3toV4, migrationV4toV5, migrationV5toV6, migrationV6toV7, migrationV7toV8] } static let migrationV1toV2 = MigrationStage.lightweight(fromVersion: TodoDataSchemaV1.self, toVersion: TodoDataSchemaV2.self) static let migrationV2toV3 = MigrationStage.lightweight(fromVersion: TodoDataSchemaV2.self, toVersion: TodoDataSchemaV3.self) static let migrationV3toV4 = MigrationStage.lightweight(fromVersion: TodoDataSchemaV3.self, toVersion: TodoDataSchemaV4.self) static let migrationV4toV5 = MigrationStage.lightweight(fromVersion: TodoDataSchemaV4.self, toVersion: TodoDataSchemaV5.self) static let migrationV5toV6 = MigrationStage.lightweight(fromVersion: TodoDataSchemaV5.self, toVersion: TodoDataSchemaV6.self) static let migrationV6toV7 = MigrationStage.lightweight(fromVersion: TodoDataSchemaV6.self, toVersion: TodoDataSchemaV7.self) static let migrationV7toV8 = MigrationStage.lightweight(fromVersion: TodoDataSchemaV7.self, toVersion: TodoDataSchemaV8.self) } @main struct DeadLineTodoApp: App { let container: ModelContainer @StateObject var store = StoreKitManager() @State var updated: Bool = false init() { do { container = try ModelContainer( for: TodoData.self, UserSetting.self, migrationPlan: TodoDataMigrationPlan.self) } catch { fatalError("Failed to initialize model container.") } } var body: some Scene { WindowGroup { ContentView(updated: $updated) .environmentObject(store) } .modelContainer(container) } }
0
0
116
1w
Is it possible to use App Attest to protect an app's CloudKit databases?
I'm a new developer who is looking to make my first app easier to manage on my end by staying in the Apple ecosystem. My ideal backend is just pure and simple CloudKit. This should help me cut down on costs and increase my security, or so I thought. The more I looked into the issue of mobile app security --more specifically, preventing fraudulent access to backend APIs-- the more it seems like CloudKit is a disaster waiting to happen. While data in transit is encrypted and there's even end-to-end encryption for private DBs, securing an app's public DB in the presence of modified apps is a daunting, if not impossible task. My assumption is that a modified app cannot be trusted to make honest assertions about itself, the device, or its iCloud account, and can potentially lie its way into restricted areas of the DB. If an app is compromised, CloudKit queries from that app can be used to make malicious queries or even changes to the databases. I'm hoping App Attest, even with its potentially circular logic, can at least make life harder for fraudsters, competitors, and vandals (when combined with other security measures like jailbreak, debugging, hooking, and tampering detections), but I have not found a single mention on how App Attest might be used to protect CloudKit. There doesn't even seem to be a verified way for me to build a third party server that can handle App Attest and then tell CloudKit to allow a user through (with all the security hazards a new developer faces when configuring an authentication server). The message seems to be: App Attest is important, but you can't use it with CloudKit, so build your own server. Questions Is my assumption that a compromised app can make malicious queries or changes to an app's CloudKit DB correct? Can App Attest be made to protect a CloudKit public DB, with or without the involvement of a third-party server to handle attestations?
0
1
88
1w
Account/data management
I am working on a social media app called "Aura Tracker" where people can add/subtract aura from people based off of their actions. I am new to app development so I don't know how to handle user accounts and aura value changing. Content view code: import SwiftUI struct ContentView: View { var body: some View { ScrollView{ VStack { Text("Aura Tracker") Image(systemName: "sparkles") .imageScale(.large) .foregroundStyle(.yellow) Text("You have "+"#"+" aura") } } } } #Preview { ContentView() } Aura_TrackerApp code: import SwiftUI @main struct Aura_TrackerApp: App { var body: some Scene { WindowGroup { ContentView() } } }
0
0
82
1w
SwiftData fatal error: Failed to locate relationship for StringCodingKey
I'm experiencing a new error in SwiftData since updating to Xcode 16/iOS 17 DB1. When passing in a model (Student) to a view and then displaying an array of Points using ForEach, I get the following fatal error: SwiftData/ModelCoders.swift:2438: Fatal error: Failed to locate relationship for StringCodingKey(stringValue: "group", intValue: nil) on Entity - name: Point superentity: subentities: storedProperties: CompositeAttribute - name: type, options: [], valueType: PointType, defaultValue: nil Properties: Attribute - name: type, options: [], valueType: String, defaultValue: nil, hashModifier: nil Relationship - name: outcome, options: [], valueType: Outcome, destination: Outcome, inverseName: nil, inverseKeypath: nil CompositeAttribute - name: proficiency, options: [], valueType: Proficiency, defaultValue: nil Properties: Attribute - name: proficiency, options: [], valueType: String, defaultValue: nil, hashModifier: nil Attribute - name: date, options: [], valueType: Date, defaultValue: nil, hashModifier: nil Attribute - name: note, options: [], valueType: String, defaultValue: nil, hashModifier: nil Relationship - name: student, options: [], valueType: Optional<Student>, destination: Student, inverseName: points, inverseKeypath: Optional(\Student.points) Attribute - name: group, options: [], valueType: Array<PersistentIdentifier>, defaultValue: [], hashModifier: nil inheritedProperties: uniquenessConstraints: indices: Xcode flags this line of the macro-generated getter of the outcome property on Point: @storageRestrictions(accesses: _$backingData, initializes: _outcome) init(initialValue) { _$backingData.setValue(forKey: \.outcome, to: initialValue) _outcome = _SwiftDataNoType() } get { _$observationRegistrar.access(self, keyPath: \.outcome) return self.getValue(forKey: \.outcome) // Fatal error: Failed to locate relationship for StringCodingKey... } set { _$observationRegistrar.withMutation(of: self, keyPath: \.outcome) { self.setValue(forKey: \.outcome, to: newValue) } } This worked just fine in iOS 17. Here's a snippet of the Student implementation: @Model class Student: Identifiable, Comparable { var name: String var number: Int @Relationship(deleteRule: .cascade, inverse: \Point.student) var points: [Point] @Relationship(deleteRule: .cascade, inverse: \Mark.student) var marks: [Mark] @Relationship(deleteRule: .nullify, inverse: \StudentGroup.students) var groups: [StudentGroup] = [] var archived: Bool } and the implementation of Point: @Model class Point: Identifiable, Comparable { var student: Student? var type: PointType var outcome: Outcome var proficiency: Proficiency var group: [Student.ID] = [] var date: Date var note: String } and finally the implementation for Outcome: @Model class Outcome: Identifiable, Comparable { var name: String var index: Int var rubric: Rubric? var proficiencies: [Proficiency] } I've tried adding a relationship in Outcome as an inverse of the outcomes property on Points (although this does not make sense in my implementation, which is why I initially did not set a relationship here) and the problem persisted. Any ideas what this error means and how I might go about fixing it?
0
0
110
1w
SwiftData History Tombstone Data is Unusable
After watching the WWDC video on the new history tracking in SwiftData, I started to update my app with this functionality. Unfortunately it seems that the current API in the first beta of Xcode 16 is rather useless in regards to tombstone data. The docs state that it would be possible to get the data from the tombstone by using a keyPath, there is no API for this however. The only thing I can do is iterate over the values (of type any) without any key information, so I do not know which data is what. Am I missing something or did we get a half finished implementation? There also does not seem to be any info on this in the release notes.
1
0
111
1w
SwiftData crashes on insert (Swift 6, Xcode 16, macOS 15)
I'm trying to insert values into my SwiftData container but it crashes on insert context.insert(fhirObject) and the only error I get from Xcode is: @Transient private var _hkID: _SwiftDataNoType? // original-source-range: /Users/cyril/Documents/GitHub/MyApp/MyApp/HealthKit/FHIR/FHIRModels.swift:35:20-35:20 configured as follows: import SwiftData import SwiftUI @main struct MyApp: App { var container: ModelContainer init() { do { let config = ModelConfiguration(cloudKitDatabase: .private("iCloud.com.author.MyApp")) container = try ModelContainer(for: FHIRObservation.self, configurations: config) UserData.shared = UserData(modelContainer: container) } catch { fatalError("Failed to configure SwiftData container.") } } var body: some Scene { WindowGroup { ContentView() .environmentObject(UserData.shared) } .modelContainer(container) } } My UserData and DataStore are configured as follows: import SwiftUI import SwiftData import os /// `FHIRDataStore` is an actor responsible for updating the SwiftData db as needed on the background thread. private actor FHIRDataStore { let logger = Logger( subsystem: "com.author.MyApp.FHIRDataStore", category: "ModelIO") private let container: ModelContainer init(container: ModelContainer) { self.container = container } func update(newObservations: [FHIRObservationWrapper], deletedObservations: [UUID]) async throws { let context = ModelContext(container) // [FHIRObservationWrapper] -> [FHIRObservation] // let modelUpdates = newObservations.lazy.map { sample in // FHIRObservation(hkID: sample.hkID, fhirID: sample.fhirID, name: sample.name, status: sample.status, code: sample.code, value: sample.value, range: sample.range, lastUpdated: sample.lastUpdated) // } do { try context.transaction { for sample in newObservations { let fhirObject = FHIRObservation(hkID: sample.hkID, fhirID: sample.fhirID, name: sample.name, status: sample.status, code: sample.code, value: sample.value, range: sample.range, lastUpdated: sample.lastUpdated) // App crashes here context.insert(fhirObject) } // for obj in modelUpdates { // // } // try context.delete(model: FHIRObservation.self, where: #Predicate { sample in // deletedObservations.contains(sample.hkID!) // }) // try context.save() logger.debug("Database updated successfully with new and deleted observations.") } } catch { logger.debug("Catch me bro: \(error.localizedDescription)") } } } @MainActor public class UserData: ObservableObject { let userDataLogger = Logger( subsystem: "com.author.MyApp.UserData", category: "Model") public static var shared: UserData! // MARK: - Properties public lazy var healthKitManager = HKManager(withModel: self) let modelContainer: ModelContainer private var store: FHIRDataStore init(modelContainer: ModelContainer) { self.modelContainer = modelContainer self.store = FHIRDataStore(container: modelContainer) } // MARK: - Methods func updateObservations(newObservations: [FHIRObservationWrapper], deletedObservations: [UUID]) { Task { do { try await store.update(newObservations: newObservations, deletedObservations: deletedObservations) userDataLogger.debug("Observations updated successfully.") } catch { userDataLogger.error("Failed to update observations: \(error.localizedDescription)") } } } } My @Model is configured as follows: public struct FHIRObservationWrapper: Sendable { let hkID: UUID let fhirID: String var name: String var status: String var code: FHIRCodeableConcept var value: FHIRLabValueType var range: FHIRLabRange? var lastUpdated: Date? } @Model public final class FHIRObservation { let hkID: UUID? let fhirID: String? @Attribute(.allowsCloudEncryption) var name: String? @Attribute(.allowsCloudEncryption) var status: String? @Attribute(.allowsCloudEncryption) var code: FHIRCodeableConcept? @Attribute(.allowsCloudEncryption) var value: FHIRLabValueType? @Attribute(.allowsCloudEncryption) var range: FHIRLabRange? @Attribute(.allowsCloudEncryption) var lastUpdated: Date? init(hkID: UUID?, fhirID: String?, name: String? = nil, status: String? = nil, code: FHIRCodeableConcept? = nil, value: FHIRLabValueType? = nil, range: FHIRLabRange? = nil, lastUpdated: Date? = nil) { self.hkID = hkID self.fhirID = fhirID self.name = name self.status = status self.code = code self.value = value self.range = range self.lastUpdated = lastUpdated } } Any help would be greatly appreciated!
2
0
173
1w
SwiftData Document-based app produces strange write errors
I have a document app built using SwiftData because frankly I'm too lazy to learn how to use FileDocument. The app's title is "Artsheets," and I'm using a document type that my app owns: com.wannafedor4.ArtsheetsDoc. The exported type identifier has these values: Description: Artsheets Document Identifier: com.wannafedor4.ArtsheetsDoc Conforms to: com.apple.package Reference URL: (none) Extensions: artsheets MIME Types: (none) And the code: ArtsheetsApp.swift import SwiftUI import SwiftData @main struct ArtsheetsApp: App { var body: some Scene { DocumentGroup(editing: Sheet.self, contentType: .package) { EditorView() } } } Document.swift import SwiftUI import SwiftData import UniformTypeIdentifiers @Model final class Sheet { var titleKey: String @Relationship(deleteRule: .cascade) var columns: [Column] init(titleKey: String, columns: [Column]) { self.titleKey = titleKey self.columns = columns } } @Model final class Column: Identifiable { var titlekey: String var text: [String] init(titlekey: String, text: [String]) { self.titlekey = titlekey self.text = text } } extension UTType { static var artsheetsDoc = UTType(exportedAs: "com.wannafedor4.artsheetsDoc") } I compiling for my iPhone 13 works, but then when creating a document I get this error: Failed to create document. Error: Error Domain=com.apple.DocumentManager Code=2 "No location available to save “Untitled”." UserInfo={NSLocalizedDescription=No location available to save “Untitled”., NSLocalizedRecoverySuggestion=Enable at least one location to be able to save documents.}
0
0
112
1w
Subject: Assistance Needed: Xcode Suggesting Unnecessary @Transient Backing Data Code for SwiftData Model
Question: Hello, I'm encountering an issue with SwiftData in Xcode. Despite setting up my model classes correctly, Xcode is suggesting additional boilerplate code for handling backing data which I believe should not be necessary. Here are the details: Context: I'm working with SwiftData to persist my data models. I've set up my model container and schema correctly, and I'm only persisting final classes. However, Xcode is suggesting the following code for one of my model classes (LoanAccount): swift Copy code @Transient private var _$backingData: any SwiftData.BackingData = LoanAccount.createBackingData() public var persistentBackingData: any SwiftData.BackingData { get { _$backingData } set { _$backingData = newValue } } static var schemaMetadata: [SwiftData.Schema.PropertyMetadata] { return [ SwiftData.Schema.PropertyMetadata(name: "loanName", keypath: \LoanAccount.loanName, defaultValue: nil, metadata: nil), SwiftData.Schema.PropertyMetadata(name: "outstandingBalance", keypath: \LoanAccount.outstandingBalance, defaultValue: nil, metadata: nil), SwiftData.Schema.PropertyMetadata(name: "currentAssetValue", keypath: \LoanAccount.currentAssetValue, defaultValue: nil, metadata: nil), SwiftData.Schema.PropertyMetadata(name: "securedAssets", keypath: \LoanAccount.securedAssets, defaultValue: [], metadata: nil) ] } required init(backingData: any SwiftData.BackingData) { _loanName = _SwiftDataNoType() _outstandingBalance = _SwiftDataNoType() _currentAssetValue = _SwiftDataNoType() _securedAssets = _SwiftDataNoType() self.persistentBackingData = backingData } @Transient private let _$observationRegistrar = Observation.ObservationRegistrar() struct _SwiftDataNoType { } My Model Setup: Here's a brief overview of my model setup: swift Copy code import Foundation import SwiftData @Model class LoanAccount: LiabilityAccount { var loanName: String var outstandingBalance: Double? var currentAssetValue: Double? var securedAssets: [SecuredAsset] = [] required init( id: UUID = UUID(), institutionName: String, accountName: String, accountBalance: Double = 0, accountOwner: String, country: String = "UK", accountCurrency: String, risk: Int = 1, accountStatus: String = "Active", startDate: Date = Date(), maturityDate: Date = Date(), dateCreated: Date = Date(), dateUpdated: Date = Date(), addressline1: String? = nil, addressline2: String? = nil, county: String? = nil, zipcode: String? = nil, phoneNumber: String? = nil, email: String? = nil, contact1: String? = nil, contact2: String? = nil, link: String? = nil, notes: String? = nil, accountNumber: String? = nil, sortCode: String? = nil, accountFee: Double? = nil, interestRate: Double? = nil, loanName: String, outstandingBalance: Double? = nil, currentAssetValue: Double? = nil, securedAssets: [SecuredAsset] = [], activities: [AccountActivity] = [] ) { self.loanName = loanName self.outstandingBalance = outstandingBalance self.currentAssetValue = currentAssetValue self.securedAssets = securedAssets super.init( id: id, institutionName: institutionName, accountName: accountName, accountType: "Loan", icon: "default_icon", accountOwner: accountOwner, country: country, accountCurrency: accountCurrency, risk: risk, accountStatus: accountStatus, startDate: startDate, maturityDate: maturityDate, dateCreated: dateCreated, dateUpdated: dateUpdated, addressline1: addressline1, addressline2: addressline2, county: county, zipcode: zipcode, phoneNumber: phoneNumber, email: email, contact1: contact1, contact2: contact2, link: link, notes: notes, accountNumber: accountNumber, sortCode: sortCode, accountFee: accountFee, interestRate: interestRate, accountBalance: accountBalance, activities: activities ) } } Issue: Xcode is suggesting that I need to add the @Transient backing data code, even though my understanding is that this should be handled automatically by SwiftData when using the @Model attribute. Request: Can anyone provide insight into why Xcode is suggesting this code and if there's a configuration or setup step I might be missing? I want to ensure my data models are set up correctly without needing unnecessary boilerplate code. Thank you!
0
0
124
1w
Document-based SwiftData apps fail to identify a store on iPad?
When trying to run my document-based iPad app using iPadOS 18 beta and Xcode 16 beta, I get an error like the following after opening a document: Thread 1: Fatal error: Failed to identify a store that can hold instances of SwiftData._KKMDBackingData<MyProject.MyModel> from [:] In order to help track down what is going wrong, I downloaded the sample app from WWDC23 session "Build an app with SwiftData" found here: https://developer.apple.com/documentation/swiftui/building-a-document-based-app-using-swiftdata When I try to run the end-state of that sample code, I get a similar error when running the app on my iPad and creating a new deck: Thread 1: Fatal error: Failed to identify a store that can hold instances of SwiftData._KKMDBackingData<SwiftDataFlashCardSample.Card> from [:] Given that the sample project is generating the same error as my own project, is this a problem with SwiftData and document-based apps in general? Or is there a change of approach that I should try?
1
1
106
1w
How to Clear System Data on Mac
How do I clear my system data on my macbook as it is taking up a huge portion of my storage? I have already tried checking if my cache folder in ~/library was too big but it is only 7.42 GB. Also, I checked if time machine was on to find snapshots but it seems I have had it off for a while now and I didn't know. Could this be causing issues and should I have it on from now on? Please help I need more storage.
0
0
103
1w
How do I handle changes from sync with Swift Data?
In Core Data, you can use a pinned query generation to make sure that your app is working from a consistent view of the data store. If you have CloudKit sync turned on, and new changes come in that invalidate relationships, your app won't see them right away as long as it's looking at a pinned query generation. Since Swift Data doesn't yet support query generations, how do I deal with this issue in Swift Data apps? For example, let's say I have an address book app. I open a particular contact, and then tap a control on the screen that opens a list of images for that contact. While looking at the images, CloudKit sync retrieves changes made by other devices, which have completely removed the parent contact. How does my app know this has happened? Suppose the image browser screen needs to refer to the parent contact, or make changes to it, but the contact is no longer there because a background sync removed it.
1
0
150
1w
API for new "Keep Downloaded" feature in iCloud Drive?
It looks like in iOS 18, there is a new option in Files to "Keep Downloaded". I.e., mark a file to be downloaded and never evicted. Is there an API that would allow us to provide this feature in our app? Our app stores files in a ubiquitous container and displays them in a custom UI (not a UIDocumentBrowserViewController). We've had a longstanding request from users that they be able to mark a file as always available locally, so that they can make sure they have access to it even if they go offline. We've done a hacky, best-effort implementation of this, but there is no truly reliable way to achieve this through the existing APIs.
1
0
123
1w
Occasional crash on `context.save()`
Recently, I noticed many crashes reported daily for context.save() in my code. I tried to resolve the issue by refactoring some of the code. My key change is to use context.performAndWait to fetch Core Data objects instead of passing them around. I refactored the code to pass NSManagedObjectID around instead of NSManagedObject itself because NSManagedObjectID is thread-safe. However, even after the refactor, the issue is still. The crash log is attached as below. I'm confused that it doesn't crash on all devices so I have no clue to find the pattern of the crashes. I also enabled -com.apple.CoreData.ConcurrencyDebug 1 on my local dev box, but seems the error cannot be caught. The new code (after I refactored) still causes the crash: private func update(movements: [InferredMovement], from visitOutObjectId: NSManagedObjectID, to visitInObjectId: NSManagedObjectID?) { let context = PersistenceController.shared.container.viewContext context.performAndWait { guard let visitOut = try? context.existingObject(with: visitOutObjectId) as? Visit else { return } var visitIn: Visit? if let visitInObjectId { visitIn = try? context.existingObject(with: visitInObjectId) as? Visit } visitOut.movementsOut.forEach { context.delete($0) } visitIn?.movementsIn.forEach { context.delete($0) } for inferred in movements { let movement = Movement(context: context) movement.type = inferred.type movement.interval = inferred.interval movement.visitFrom_ = visitOut movement.visitTo_ = visitIn } visitOut.objectWillChange.send() context.saveIfNeeded() } } Note, saveIfNeeded() is an extension function implemented as: extension NSManagedObjectContext { /// Only performs a save if there are changes to commit. @discardableResult public func saveIfNeeded() -> Error? { guard hasChanges else { return nil } do { try save() return nil } catch { defaultLogger.error("Core Data Error: Failed to save context") return error } } } Crash context
1
0
100
1w
iCloud Synchronization doesn’t work
I’m trying to sync data from the AppData on one device to another device with the same iCloud. It uploads the data to the CloudKit but it doesn’t write the data it fetches from the cloud into the AppData storage. It should store a timestamp, a few integers, and two lists of integers. The lists are both optional and store numbers. They can have 0 up to 50 numbers in them. This is the part where it should fetch the records and store them in the AppData let container = CKContainer(identifier: "iCloud.com.calchunt") let privateDatabase = container.privateCloudDatabase let dispatchGroup = DispatchGroup() var errors: [Error] = [] // Leere Liste zum Speichern neuer Spielsitzungen aus der Cloud var newGameSessions: [AppModule.GameSession] = [] for gameSession in gameSessions { let recordIDString = gameSession.id.uuidString // UUID zu String umwandeln let recordID = CKRecord.ID(recordName: recordIDString) dispatchGroup.enter() privateDatabase.fetch(withRecordID: recordID) { (existingRecord, error) in defer { dispatchGroup.leave() } if let error = error { // Fehler beim Abrufen des Records print("Fehler beim Abrufen des Records aus CloudKit: \(error.localizedDescription)") errors.append(error) } else if let existingRecord = existingRecord { // Record existiert in der Cloud print("Record mit ID \(existingRecord.recordID.recordName) existiert in CloudKit") // à berprüfen, ob der Record bereits im AppModule vorhanden ist if let _ = gameSessions.firstIndex(where: { $0.id == gameSession.id }) { // Record existiert bereits im AppModule, überspringe das Speichern print("Record mit ID \(existingRecord.recordID.recordName) existiert bereits im AppModule, überspringe das Speichern") } else { // Record existiert nicht im AppModule, füge ihn zur Liste der neuen Spielsitzungen hinzu let newGameSession = AppModule.GameSession( id: gameSession.id, losungszahl: gameSession.losungszahl, elapsedTime: gameSession.elapsedTime, currentDate: gameSession.currentDate, skipped: gameSession.skipped, skipped2: gameSession.skipped2, level: gameSession.level ) newGameSessions.append(newGameSession) print("Record mit ID \(existingRecord.recordID.recordName) wird zum AppModule hinzugefügt") } } else { // Record existiert nicht in der Cloud print("Record mit ID \(recordID.recordName) existiert nicht in CloudKit") } } } dispatchGroup.notify(queue: .main) { if !errors.isEmpty { for error in errors { print("Fehler beim Abrufen der Daten aus CloudKit: \(error.localizedDescription)") } } else { // Füge neue Spielsitzungen zum AppModule hinzu gameSessions.append(contentsOf: newGameSessions) // Speichere die aktualisierten Daten im AppStorage do { let encoder = JSONEncoder() let gameSessionsData = try encoder.encode(gameSessions) GameSessions = gameSessionsData print("Daten erfolgreich aus CloudKit geladen und im AppStorage gespeichert") } catch { print("Fehler beim Codieren und Speichern der Daten im AppStorage: \(error.localizedDescription)") } } } }
1
0
105
1w
CloudKit Request - CKAsset size limit and public database storage per active user
Hello, I had a WWDC Lab with two CloudKit engineers who asked me to file a "Feedback Request" for critical information regarding CloudKit. I've filed the FB and have also decided to post a forum post to increase my chances of having these critical questions answered. If allowed, I will also post responses to my FB here. CKAssets I would like to know how large assets attached to a CKAsset can get before being rejected by the system. If the figure differs for private and public databases, please also let me know. CloudKit pricing information There used to be pricing information available on the website, but there's basically no information now. This makes it hard to calibrate user upload limits for my app in order to avoid overage fees. I'm not looking to game the system, (something this strange opaqueness is likely meant to prevent); I'm just looking to avoid a situation where competitors and vandals abuse my the content upload system so I get smacked by large bills out of nowhere. A rough figure of how many GB of data each active user adds to my app's CloudKit public database would suffice. While we're at it, if I have two apps that share a public database (if that's possible), do the active user counts of both contribute to the public database's free threshold?
0
0
118
1w
SwiftData Custom Datastore Docs and Implementation
I have watched the following WWDC 2024 sessions: What’s new in SwiftData Create a custom data store with SwiftData Platform State of the Union Now, I have an application that exposes a GraphQL API endpoint that's using PostgreSQL Server 16.3 database. Next, this API returns JSON to the client application (i.e. SwiftUI app). Furthermore, I have checked the current documentation and the above videos appear to be the best reference at this time. My proposed architecture looks like the following: SwiftUI <--> SwiftData <--> PostgreStoreConfiguration && PostgreStore TBD <--> GraphQL API <--> PostgreSQL Thus, I have the following questions: Are there plans to add common out-of-the-box data store implementations for PostgreSQL, Cassandra, Redis, and so on? Will it be possible to implement data stores built to use gRPC, GraphQL, REST, and others to name a few? Will there be more documentation on the actual creation of a custom data store because the current documentation provides a slim API reference? I look forward to your feedback regarding the SwiftData custom data stores.
1
0
219
1w
CloudKit in TestFlight: No sync between devices 😭
I have read and tried all the possible solutions available online, but still didn't get a result. My multi-platform iOS/macOS app uses private databases in iCloud with Core Data. All works as expected when I build the app from Xcode to my multiple devices: data is being synced. But when I upload the app to TestFlight, data is not being synced. This is what I have already tried: In CloudKit Dashboard, I reset the schema and deployed schema changes from the development to production. In Xcode project settings, in Targets, under Frameworks, Libraries... I added the CloudKit.framework, set as "do not embed". In Xcode project settings, under Signing & Capabilities, all the CloudKit, Background fetch and Remote notifications checkboxes are enabled for both Debug and Release. They all point to the same correct iCloud container. In Xcode project settings, under Build Settings, Code Signing Entitlements for both Debug and Release point to the same entitlements file. In .entitlements file, CloudKit container identifier points to the correct container. iCloud Services set to CloudKit. In .entitlements file, APS Environment for both iOS and macOS is set as "production". In Core Data .xcdatamodeld file, under Configurations, I have a Default option, and it is being set to "Used with CloudKit." Each time I upload new version to the TestFlight, I delete all the previous versions from all my devices, so development and production containers are not mixed up in any way. I understand that I may be missing something. But after researching all the resources available online, I didn't find anything else to configure or to add in this setup. I want to point out again that data is not being synced only in TestFlight, and thus, possibly, after release. Whenever I build app directly to the device from Xcode, all works as expected. I hope someone can help me.
2
0
132
1w