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

I want to display the results of a search in SwiftData and replace the data.
Sorry for the elementary question.
In the following case in SwiftData, can I display the results of the search and replace text = "Test" with text = "Test2"? // Serch let test = #Predicate<GroupItem> { testitem in testitem.text.contains("Test") } I'm having trouble understanding the database because I can't replace the data that I searched for to see if the search was successful or not. @Model class Item { var id: Int var groupItem: [GroupItem]? init(id: Int) { self.id = id } } @Model class GroupItem { var groupId: Int var text: String init(groupId: Int, text:String) { self.groupId = groupId self.text = text } } struct ContentView: View { @Environment(\.modelContext) private var modelContext @Query private var items: [Item] var body: some View { NavigationSplitView { List { ForEach(items) { item in NavigationLink { Text("Item at \(item.id)") } label: { Text("\(item.id)") } } .onDelete(perform: deleteItems) } .toolbar { ToolbarItem(placement: .navigationBarTrailing) { EditButton() } ToolbarItem { Button(action: addItem) { Label("Add Item", systemImage: "plus") } } ToolbarItem { Button(action: serchItems) { Text("Serch") } } } } detail: { Text("Select an item") } } private func addItem() { withAnimation { let newItem = Item(id: 0 + 1) let newItem2 = GroupItem(groupId: 0 + 1, text: "Test") modelContext.insert(newItem) modelContext.insert(newItem2) } } private func deleteItems(offsets: IndexSet) { withAnimation { for index in offsets { modelContext.delete(items[index]) } } } private func serchItems() { // Serch let test = #Predicate<GroupItem> { testitem in testitem.text.contains("Test") } } } #Preview { ContentView() .modelContainer(for: Item.self, inMemory: true) .modelContainer(for: GroupItem.self, inMemory: true) }
0
0
258
Sep ’23
How to check if data is fetched from CloudKit?
When using CloudKit in an app, if there are data changes on other devices being synchronized, and you also want to make changes to the data on the current device and reflect it back to the CloudKit server, you might want to display a native loading icon, like the one you see in the Notes app, during this process. How can you implement this? If anyone knows how to do it using SwiftUI, please let me know.
0
0
283
Sep ’23
Cloudkit + Watch - Invalid bundle ID for container
I'm running into a problem getting CloudKit to work with a watch app I'm adding to my existing iOS app. I've created a new target for a watch app, and on boot on my real watch, I'm getting the following error: com.apple.coredata.cloudkit.zone:__defaultOwner__ = <CKError 0x14e455f0: "Permission Failure" (10/2007); server message = "Invalid bundle ID for container" My iOS app has the bundle ID of stevenquinn.POS-Chickens and my watch app is stevenquinn.POS-Chickens.watchkitapp. I'm using NSPersistentCloudKitContainer in a shared Persistence file that's accessible by both targets. Both targets have the same iCloud capabilities and containers checked. Any tips on where I might be running wrong?
1
0
374
Sep ’23
SwiftData Macros don't seem to work
I'm following the Build an app with SwiftData from WWDC 2023. I'm using the Xcode release candidate for Xcode 15. i'm running the Developer Beta for Sonoma. The first change was to import SwiftData, add the @Model macro to the Definition for the Card object and remove @Published from two variable in the definition. After doing this I get 5 errors: External macro implementation type 'SwiftDataMacros.PersistentModelMacro' could not be found for macro 'Model()' The instructions continue to the CardEditorView and change the macro for var card to @Bindable with the error 'init(wrappedValue:)' is unavailable: The wrapped value must be an object that conforms to Observable Then we move to the App main class where we add .modelContainer(for: Card.self) and get the error No exact matches in call to instance method 'modelContainer' Any clue why this is happening?
2
1
849
Sep ’23
Fetch recurring objects using CoreData predicate
Hello! I was wondering if there's any open source example how to implement SUBQUERY in CoreData in calendar based app? For example: User creates an event with subtasks on the 1st on September with daily frequency On the 5th of September they update just that day event's details, some subtasks. On the 7th of September they see the same event that was created on the 1st of September. Structs that can describe the case may look like this: enum Frequency { case daily case weekly case monthly } struct Subtask { var name: String var isCompleted: Bool } struct Event { var id: UUID var name: String var startAt: Date var repeatUntil: Date? var isCompleted: Bool var subtasks: [Subtask] var frequency: Frequency? var excludedOn: [Date] } For each day on a week I need to fetch events from CoreData, so I'm wondering how predicate can look like in such case? I met SUBQUERY, but I'm not sure how to apply weekly and monthly frequency frequency into NSPredicate (for daily it's pretty straightforward). Would be glad for any advices! ~Paul
0
0
275
Sep ’23
#Predicate doesn't work with enum
Problem The following code doesn't work: let predicate = #Predicate<Car> { car in car.size == size //This doesn't work } Console Error Query encountered an error: SwiftData.SwiftDataError(_error: SwiftData.SwiftDataError._Error.unsupportedPredicate) Root cause Size is an enum, #Predicate works with other type such as String however doesn't work with enum Enum value is saved however is not filtered by #Predicate Environment Xcode: 15.0 (15A240d) - App Store macOS: 14.0 (23A339) - Release Candidate Steps to reproduce Run the app on iOS 17 or macOS Sonoma Press the Add button Notice that the list remains empty Expected behaviour List should show the newly created small car Actual behaviour List remains empty inspite of successfully creating the small car. Feedback FB13194334 Code Size enum Size: String, Codable { case small case medium case large } Car import SwiftData @Model class Car { let id: UUID let name: String let size: Size init( id: UUID, name: String, size: Size ) { self.id = id self.name = name self.size = size } } ContentView struct ContentView: View { var body: some View { NavigationStack { CarList(size: .small) } } CarList import SwiftUI import SwiftData struct CarList: View { let size: Size @Environment(\.modelContext) private var modelContext @Query private var cars: [Car] init(size: Size) { self.size = size let predicate = #Predicate<Car> { car in car.size == size //This doesn't work } _cars = Query(filter: predicate, sort: \.name) } var body: some View { List(cars) { car in VStack(alignment: .leading) { Text(car.name) Text("\(car.size.rawValue)") Text(car.id.uuidString) .font(.footnote) } } .toolbar { Button("Add") { createCar() } } } private func createCar() { let name = "aaa" let car = Car( id: UUID(), name: name, size: size ) modelContext.insert(car) } }
5
1
1.3k
Sep ’23
Creation of ModelContainer in case of transition to other views with NavigationLink
Sorry for the rudimentary question, SwiftData question.
In the case of Xcode standard sample code, @main struct SwiftDataTestProjectsApp: App { var sharedModelContainer: ModelContainer = { let schema = Schema([ Department.self,. ]) let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false) do { return try ModelContainer(for: schema, configurations: [modelConfiguration]) } catch { fatalError("Could not create ModelContainer: \(error)") } }() var body: some Scene { WindowGroup { ContentView() } .modelContainer(sharedModelContainer) } } and create a ModelContainer for the Scene, #Preview { ContentView() .modelContainer(for: Item.self, inMemory: true) } However, if SwiftData is not used in the ContentView, and only if the transition is made to the other view using NavigationLink, as shown in the code below, a ModelContainer is created and a ModelContainer is specified for the ContentTwoView, If I want to specify a separate container for ContentTwoView, how should I create .modelContainer(sharedModelContainer) and specify .modelContainer(for: Item.self, inMemory: true)? Should I continue to create the ModelContainer for the Scene as before? Or is there a way to create it only for the specified View and specify it there? struct ContentView: View { var body: some View { NavigationStack { NavigationLink("ContentTwoView") { ContentTwoView()) } } } } struct ContentTwoView: View { @Environment(\.modelContext) private var modelContext @Query private var items: [Item]. var body: some View {
1
0
556
Sep ’23
SwiftData Crashes After Modifying The VersionedSchema More Than Once
I've been stuck on this one for quite a while now, and I'm starting to become more and more convinced this is an issue with Xcode 15 Beta RC. Just to give you some context I seem to be getting the following crash after modifying my schema (adding new properties) for the the second time. Below is the crash that is occurring on my device & simulator. Unresolved error loading container Error Domain=NSCocoaErrorDomain Code=134130 "Persistent store migration failed, missing source managed object model." UserInfo={URL=file:///Users/xxxxx/Library/Developer/CoreSimulator/Devices/23B8CDDD-CC5F-4A1C-B0F4-CF89C77B7ECF/data/Containers/Data/Application/235A14D7-6492-439F-BB4D-B18498D80970/Library/Application%20Support/default.store, metadata={ NSPersistenceFrameworkVersion = 1327; NSStoreModelVersionChecksumKey = "dia3s8Q2+lqw669j9+RcPLQ+06yu0x6BBTZ4cXoQ1os="; NSStoreModelVersionHashes = { Category = {length = 32, bytes = 0x187754bb 36c51a62 85ede16f 4b2a3912 ... 57326030 2de7ef77 }; Item = {length = 32, bytes = 0xa7e4be4d ddd86d36 f71799b0 bc69dcb4 ... 83d47dfe d433fc01 }; }; NSStoreModelVersionHashesDigest = "G/Tk4lzyeNBXzf5+7qxbd+isF8uFnSaC5LtUCCkC8GQwaG1d9Di0eJ10NQEyPgwRczoYeYAMYG8ai4RooEhH9w=="; NSStoreModelVersionHashesVersion = 3; NSStoreModelVersionIdentifiers = ( "1.2.0" ); NSStoreType = SQLite; NSStoreUUID = "A99894EA-FA7B-4CA7-AEB7-6DEE42843EC0"; "_NSAutoVacuumLevel" = 2; }, reason=Can't find model for source store} I currently have 5 versions of my Schemas there's two of them Item Category Below is a minified changelog of what has changed between versions. Version 1 (Initial Version) Version 2 (Lightweight Migration - Property is renamed in Item) Version 3 (Custom Migration - New Property is added to Item both are bools) Version 4 (Custom Migration - New Property is added to Category which is a transformable) Version 5 (Custom Migration - New Property is added to Item which is a string) It's quite a large file with all of the version schema's etc so i've created a gist here for you to see all of the changes that have been made between Version 1 up until Version 5. The problem that I'm seeing is that between migration for V1 up until V4 everything is fine. It's only until SwiftData attempt to migrate V4 to V5 and I get the crash that I have provided above, and V5 only has a new string property which shouldn't be causing a crash since I've done 2 custom migrations that were all fine before V5 so this seems really strange even tho my migration plan is setup properly which you can see below. enum ToDosMigrationPlan: SchemaMigrationPlan { static var schemas: [VersionedSchema.Type] { [ToDosSchemaV1.self, ToDosSchemaV2.self, ToDosSchemaV3.self, ToDosSchemaV4.self, ToDosSchemaV5.self] } static var stages: [MigrationStage] { [ migrateV1toV2, migrateV2toV3, migrateV3toV4, migrateV4toV5 ] } // V1 to V2 static let migrateV1toV2 = MigrationStage.lightweight( fromVersion: ToDosSchemaV1.self, toVersion: ToDosSchemaV2.self ) // V2 to V3 static let migrateV2toV3 = MigrationStage.custom( fromVersion: ToDosSchemaV2.self, toVersion: ToDosSchemaV3.self, willMigrate: nil, didMigrate: { context in let items = try? context.fetch(FetchDescriptor<ToDosSchemaV3.Item>()) items?.forEach { item in item.isFlagged = false item.isArchived = false } try? context.save() }) static let migrateV3toV4 = MigrationStage.custom( fromVersion: ToDosSchemaV3.self, toVersion: ToDosSchemaV4.self, willMigrate: nil, didMigrate: { context in let categories = try? context.fetch(FetchDescriptor<ToDosSchemaV4.Category>()) categories?.forEach { category in category.color = UIColor(possibleColors.randomElement()!) } try? context.save() }) static let migrateV4toV5 = MigrationStage.custom( fromVersion: ToDosSchemaV4.self, toVersion: ToDosSchemaV5.self, willMigrate: nil, didMigrate: { context in // TODO: Handle setting some custom data here with defaults }) } Has anyone come across this or got any ideas as to what the problem may be?
4
1
1.8k
Sep ’23
SwiftData @Query crashes when trying to filter or sort using an enum or relationship
Like the title says, I've realised that when I try to use filter or sort on properties that aren't standard supported data types i.e. Using a transformable or a value type like an enum, I seem to be getting the following crash... SwiftData/DataUtilities.swift:1140: Fatal error: Unexpected type for Expansion: Optional<UIColor> Xcode expands and shows me when trying to access the wrapped value it's crashing. I'm assumung that the query property wrapper can't handle these custom data types @Query private var items: [Item] { get { _items.wrappedValue <--- Crash here } } Which seems to be pointing to a transferable property in one of my models. Below are my two models i'm using. enum Priority: Int, Codable, Identifiable, CaseIterable { case low case medium case high var title: String { switch self { case .low: return "Low" case .medium: return "Medium" case .high: return "High" } } var image: Image? { switch self { case .medium: return Image(systemName: "exclamationmark.2") case .high: return Image(systemName: "exclamationmark.3") default: return nil } } var id: Self { self } } @Model final class Item: Codable { var title: String @Attribute(originalName: "timestamp") var dueDate: Date var isCompleted: Bool var isFlagged: Bool = false var isArchived: Bool = false var isCritical: Bool? var priority: Priority? @Relationship(deleteRule: .nullify, inverse: \Category.items) var category: Category? @Attribute(.externalStorage) var image: Data? enum CodingKeys: String, CodingKey { case title case timestamp case isCritical case isCompleted case category case imageName } init(title: String = "", dueDate: Date = .now, priority: Priority? = nil, isCompleted: Bool = false) { self.title = title self.dueDate = dueDate self.priority = priority self.isCompleted = isCompleted } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.title = try container.decode(String.self, forKey: .title) self.dueDate = Date.randomDateNextWeek() ?? .now self.isCompleted = try container.decode(Bool.self, forKey: .isCompleted) self.category = try container.decodeIfPresent(Category.self, forKey: .category) if let imageName = try container.decodeIfPresent(String.self, forKey: .imageName), let imageData = UIImage(named: imageName) { self.image = imageData.jpegData(compressionQuality: 0.8) } if let isCritical = try container.decodeIfPresent(Bool.self, forKey: .isCritical), isCritical == true { self.priority = .high } } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(title, forKey: .title) try container.encode(dueDate, forKey: .timestamp) try container.encode(isCompleted, forKey: .isCompleted) try container.encode(category, forKey: .category) } } @Model class Category: Codable { @Attribute(.unique) var title: String var items: [Item]? @Attribute(.transformable(by: ColorValueTransformer.self)) var color: UIColor? init(title: String = "", color: UIColor) { self.title = title self.color = color } enum CodingKeys: String, CodingKey { case title } required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.title = try container.decode(String.self, forKey: .title) self.color = UIColor(possibleColors.randomElement()!) } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(title, forKey: .title) } } And below is an example of me sorting based on my enum (Priority) & Relationship (Category name) func sort() -> [SortDescriptor<Item>]{ switch self { case .title: [SortDescriptor(\Item.title)] case .date: [SortDescriptor(\Item.dueDate)] case .category: [SortDescriptor(\Item.category?.title)] case .priority: [SortDescriptor(\Item.priority?.rawValue)] } } And a filter example below creating a predicate that we will execute to return and matches found in the title or category title let highPriority = Priority.high if let query { return #Predicate { $0.priority == highPriority && ($0.title.contains(query) || $0.category?.title.contains(query) == true) && $0.isArchived == false } } I'm pretty sure this is a SwiftData bug since when using strings, bools and dates it's all fine using anything outside of that box causes these crashes...
8
1
2.1k
Sep ’23
SwiftData errors when trying to insert multiple objects
I have two models: @Model class User: Codable { @Attribute(.unique) var username: String @Attribute(.unique) var email: String var firstName: String var lastName: String @Attribute(.unique) var id: Int @Relationship(inverse: \House.members) var houses: [House] = [] init(username: String, email: String, firstName: String, lastName: String, id: Int) { self.username = username self.email = email self.firstName = firstName self.lastName = lastName self.id = id } enum CodingKeys: String, CodingKey { case username case email case firstName = "first_name" case lastName = "last_name" case id } required init(from decoder: Decoder) throws { ... } func encode(to encoder: Encoder) throws { ... } } and @Model class House: Codable { var name: String var city: String var address: String @Attribute(.unique) var id: Int var ownerID: Int var members: [User] init(name: String, city: String, address: String, id: Int, ownerID: Int, members: [User]) { self.name = name self.city = city self.address = address self.id = id self.ownerID = ownerID self.members = members } enum CodingKeys: String, CodingKey { case name case city case address case id case ownerID = "owner_id" case members } required init(from decoder: Decoder) throws { ... } func encode(to encoder: Encoder) throws { ... } } I want to save a list of House objects I receive in JSON format: [ { "name": "A", "city": "A", "address": "A", "id": 1, "owner_id": 1, "members": [ { "username": "A", "email": "A", "first_name": "A", "last_name": "A", "id": 1 } ] } ... ] This is the code I use: import SwiftUI import SwiftData struct HouseListView: View { @Environment(\.modelContext) var modelContext @Query(sort: \House.name) var houses: [House] var body: some View { NavigationStack { List { ForEach(houses) { house in Text(house.name) } } .task { if let houses = await getHouses() { do { for house in houses { modelContext.insert(house) } try modelContext.save() } catch { print(error) } } } } } } But I receive the following errors: Error Domain=NSCocoaErrorDomain Code=1560 "Multiple validation errors occurred." UserInfo={NSDetailedErrors=( "Error Domain=NSCocoaErrorDomain Code=1570 \"%{PROPERTY}@ is a required value.\" UserInfo={NSValidationErrorObject=<NSManagedObject: 0x2827cc8c0> (entity: User; id: 0x2804967e0 <x-coredata:///User/tAC4F0253-65B0-4C92-846F-8E72A8E115277>; data: {\n email = nil;\n firstName = nil;\n houses = (\n );\n id = nil;\n lastName = nil;\n username = nil;\n}), NSLocalizedDescription=%{PROPERTY}@ is a required value., NSValidationErrorKey=email, NSValidationErrorValue=null}", "Error Domain=NSCocoaErrorDomain Code=1570 \"%{PROPERTY}@ is a required value.\" UserInfo={NSValidationErrorObject=<NSManagedObject: 0x2827cc8c0> (entity: User; id: 0x2804967e0 <x-coredata:///User/tAC4F0253-65B0-4C92-846F-8E72A8E115277>; data: {\n email = nil;\n firstName = nil;\n houses = (\n );\n id = nil;\n lastName = nil;\n username = nil;\n}), NSLocalizedDescription=%{PROPERTY}@ is a required value., NSValidationErrorKey=firstName, NSValidationErrorValue=null}", "Error Domain=NSCocoaErrorDomain Code=1570 \"%{PROPERTY}@ is a required value.\" UserInfo={NSValidationErrorObject=<NSManagedObject: 0x2827cc8c0> (entity: User; id: 0x2804967e0 <x-coredata:///User/tAC4F0253-65B0-4C92-846F-8E72A8E115277>; data: {\n email = nil;\n firstName = nil;\n houses = (\n );\n id = nil;\n lastName = nil;\n username = nil;\n}), NSLocalizedDescription=%{PROPERTY}@ is a required value., NSValidationErrorKey=id, NSValidationErrorValue=null}", "Error Domain=NSCocoaErrorDomain Code=1570 \"%{PROPERTY}@ is a required value.\" UserInfo={NSValidationErrorObject=<NSManagedObject: 0x2827cc8c0> (entity: User; id: 0x2804967e0 <x-coredata:///User/tAC4F0253-65B0-4C92-846F-8E72A8E115277>; data: {\n email = nil;\n firstName = nil;\n houses = (\n );\n id = nil;\n lastName = nil;\n username = nil;\n}), NSLocalizedDescription=%{PROPERTY}@ is a required value., NSValidationErrorKey=lastName, NSValidationErrorValue=null}", "Error Domain=NSCocoaErrorDomain Code=1570 \"%{PROPERTY}@ is a required value.\" UserInfo={NSValidationErrorObject=<NSManagedObject: 0x2827cc8c0> (entity: User; id: 0x2804967e0 <x-coredata:///User/tAC4F0253-65B0-4C92-846F-8E72A8E115277>; data: {\n email = nil;\n firstName = nil;\n houses = (\n );\n id = nil;\n lastName = nil;\n username = nil;\n}), NSLocalizedDescription=%{PROPERTY}@ is a required value., NSValidationErrorKey=username, NSValidationErrorValue=null}", "Error Domain=NSCocoaErrorDomain Code=1570 \"%{PROPERTY}@ is a required value.\" UserInfo={NSValidationErrorObject=<NSManagedObject: 0x2827cca00> (entity: User; id: 0x280496a80 <x-coredata:///User/tAC4F0253-65B0-4C92-846F-8E72A8E115279>; data: {\n email = nil;\n firstName = nil;\n houses = (\n );\n id = nil;\n lastName = nil;\n username = nil;\n}), NSLocalizedDescription=%{PROPERTY}@ is a required value., NSValidationErrorKey=email, NSValidationErrorValue=null}", "Error Domain=NSCocoaErrorDomain Code=1570 \"%{PROPERTY}@ is a required value.\" UserInfo={NSValidationErrorObject=<NSManagedObject: 0x2827cca00> (entity: User; id: 0x280496a80 <x-coredata:///User/tAC4F0253-65B0-4C92-846F- ..... )} ForEach<Array<House>, Int, Text>: the ID 3 occurs multiple times within the collection, this will give undefined results!
3
3
824
Sep ’23
List of relationship members fails to update when member content changes
FB13099793 I have a view which lists detail information about a SwiftData object, including a list of the members of its relationship. The Problem: If I use a modal presentation to edit the content of a relationship-member, upon return, the member has been updated, but the view falis to show it. The view updates correctly on adding a new member to the relationship, deleting a member, etc. But I cannot get the List to update if the content of the member changes (in a modal presentation). A few requirements that may be of significance: (1) The relationship (and inverse) are defined as optional because it is an eventual requirement for this app to use CloudKit synchronization. (2) The display of the members must be ordered. For this reason, the member object contains a "ordinal" property which is used to sort the the members. The relevant parts of the models are: @Model final public class Build { public var bld: Int @Relationship(inverse: \ChecklistItem.build) public var checklist: [ChecklistItem]? public init(bld: Int) { self.bld = bld self.checklist = [] } } @Model final public class ChecklistItem { public var ordinal: Int public var title: String public var subtitle: String // etc. public var build: Build? public init(build: Build) { self.ordinal = -1 self.title = "" self.subtitle = "" self.build = build } } The relevant parts of the view which handles the display is shown below. (Please look at the notes that follow the code for a discussion of some issues.) struct buildDetailChecklistView: View { @Environment(\.modelContext) var context: modelContext @State private var selectedItem: ChecklistItem? = nil @Bindable var build: Build init(build: Build) { self.build = Build } var body: some View { VStack { // ... some other stuff } List { ForEach((build.checklist ?? []) .sorted(by: { (a,b) in a.ordinal < b.ordinal})) { item in RowView(item) // displays title, subtitle, etc. .swipeActions(edge: .trailing, allowsFullSwipe: false) { Button { deleteRow(item) } label: { Label("Delete", systemImage: "trash") } .tint(.red) } .swipeActions(edge: .leading, allowsFullSwipe: false) { Button { selectedItem = item } label: { Label("Edit", systemImage: "pencil.line") } .tint(.blue) } } .sheet(item: $selectedItem) { item in BuildDetailAddEditChecklistItem(item: item, handler: updateChecklist(_:)) } } } private func updateChecklist(_ item: ChecklistItem) { if let index = build.checklist!.firstIndex(where: { $0 == item }) { DispatchQueue.main.async { [index] in build.checklist!.remove(at: index) try? context.save() build.checklist!.insert(item, at: index) } } } } Notes: (1) I cannot use a @Query macro in this case because of limitations in #Predicate. Every predicate I tried (to match the ChecklistItem's build member with it's parent's build object crash.) (2) I don't want to use @Query anyway because there is no need for the extra fetch operation it implies. All of the data is already present in the relationship. There ought to be a new macro/propertyWrapper to handle this. (3) Dealing with the required sort operation on the relationship members [in the ForEach call] is very awkward. There ought to be a better way. (4) The BuildDetailAddEditChecklistItem() function is a modal dialog, used to edit the content of the specified ChecklistItem (for example, changing its subtitle). On return, I expected to see the List display the new contents of the selected item. IT DOES NOT. (5) The handler argument of BuildDetailAddEditChecklist() is one of the things I tried to "get the List's attention". The handler function is called on a successful return from the model dialog. The implementation of the handler function finds the selected item in the checklist, removes it, and inserts it back into the checklist. I expected that this would force an update, but it does not.
0
1
352
Sep ’23
Desktop files lost when I disconnected iCloud
My iCloud storage was full, and I noticed my MacBook was backing up to iCloud, which I didn't know - we just thought we were using iCloud backup for our iPhones. So to free up space, I disconnected iCloud from my MacBook - when I did, everything saved on my desktop disappeared. The issue is that iCloud was full, so these files weren't backed up - now they are just gone. They aren't in my deleted items folder and they aren't in iCloud. I don't understand why disconnecting iCloud from my MacBook would permanently remove files that were saved on my desktop. Does anyone know if there is a way to restore files from the desktop in a situation like this?
1
0
598
Sep ’23
Saving to Core Data during device locking & unlocking
The following error message "SIGABRT: This NSPersistentStoreCoordinator has no persistent stores (device locked). It cannot perform a save operation" has indicated need to provide for sequencing of the Core Data context saving operation. We want to avoid .save() if locking is in flight, also postpone .save() until unlocking has completed. Currently our .save() is bracket by do-catch block but this is notably not helping in the case of SIGABR signal Given that our saving operations must take place synchronously, what is the recommended practice to implement such sequencing with respect to locking / unlocking
0
0
313
Sep ’23
iCloud.com app access
Apple has consolidated users iCloud data into iCloud.com. our app uses iCloud to sync data between iOS devices - iPad and iPhone using Core Data and iCloud Documents. But, this data is not posted on iCloud.com. It would be very useful, especially when iCloud fails to sync. When Apple does an Upgrade, say going from iOs 16to 17 and no way to retrieve the data. Any other developers concur?
1
0
407
Sep ’23
How to fix NSCloudKitMirroringDelegate unhandled exception after faulty model change
I have a complex data model in development mode, with a large amount of data, using CoreData with CloudKit sync. All worked fine, syncing from a Mac to an iPad Pro, until I made some unwise changes to the model and a couple of relationships. I should have known, but was hurrying and not thinking clearly. The App is not on the App Store: it's for my own use. Records are now not synced to CloudKit: _error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _importFinishedWithResult:importer:]- (1371): <PFCloudKitImporter: 0x6000005d8080>: Import failed with error: Error Domain=NSCocoaErrorDomain Code=134421 "Import failed because applying the accumulated changes hit an unhandled exception." UserInfo={NSLocalizedFailureReason=Import failed because applying the accumulated changes hit an unhandled exception., NSUnderlyingException=* -[__NSPlaceholderArray initWithObjects:count:]: attempt to insert nil object from objects[0]}_** It seems that there's a queue of faulty (non-matching) updates, which I can find no way of purging. Perhaps I could disconnect the CloudKit syncing in the app, use the CloudKit console to reset the development environment, then reconnect CloudKit syncing in the app - but would that invoke a repopulation of the CloudKit data, or cause a deletion of all CoreData data? I can, with a few days' work, reimport all of the data - but that would, I assume, need a newly named app so as to create a new CloudKit container. Any thoughts/solutions would be appreciated. Regards, Michaela
4
0
750
Sep ’23
How does SwiftData schema migration work and what are the possible schema changing operations
I am trying out SwiftData schema migration to see what is possible. I understand from the WWDC23 sessions that I can rename properties (as an example of a lightweight migration) and make properties unique (as an example of a custom migration) This has worked well and promising. But I have tried unsuccessfully to add a new property to an existing model, resulting in fatal errors, like Fatal error: Expected only Arrays for Relationships Also, I failed adding a new Model to an existing schema with different fatal errors depending on my try-and-error coding. Questions In a migration stage, I have access to a model context. How does this reflect the old and new schema? For example if I rename a model, will I have access to both the old and new model? Are there any examples of doing complex migrations yet? What are the currently supported migration operations besides making an attribute unique and renaming an attribute? Any pointer to a more in-depth documentation will be appreciated.
3
0
1.4k
Oct ’23