I am developing "Tasty Recipes" app. I want to load all data related to this app such "Recipe Category", "Recipes List", "Recipes Inscredient", "Preparation Methods" and so on. How can I load and store all data using SwiftData. User is going to use these data. They will update few things like "Favourite Recipes", "Rating". How can I do this.
iCloud & Data
RSS for tagLearn how to integrate your app with iCloud and data frameworks for effective data storage
Post
Replies
Boosts
Views
Activity
I'm experiencing an unresponsive UI since MacOS 14.0 and iOS 17.0 when calling record(for: ) or recordID(for:) on the instance of NSPersistentCloudKitContainer.
On MacOS, the UI freeze almost always happens when calling the function.
On iOS, it is necessary that the device (or simulator) does not have any network connection.
I would like to ask if anyone experienced the same problem. I have posted the problem twice to Apple via the Feedback app (once for iOS and once for MacOS). No reply yet on MacOS but on iOS Apple marked it as resolved because apparently no one but me has experienced this problem.
In the meantime, I have set up a minimum reproducible example app (MRE).:
https://github.com/DominikButz/NotesApp-Cloud-Kit-Record-UI-Freeze-
Anyone interested, please read the readme of the repository. It includes step by step instructions on how to reproduce the bug.
I can't rule out I have misunderstood the usage of CoreData and CloudKit - in that case please point me in the right direction.
The app I'm working on should also work offline (and on MacOS!) but it doesn't do so properly as long as this bug exists.
I'm exploring switching to SwiftData (which would mean no one using macOS 13 / iOS 16 can use my app...) but I would still need to access cloud kit records even with SwiftData and I fear the bug also exists in SwiftData.
Thanks
I need to track user actions, for example video view count. Then the data is used to get most popular videos for last 7 days, 30 days and for a year. For this purpose I have created a Downloads table with timestamp and video fields.
Each time user opens the catalog, I'm running queries to get Downloads and sort the videos based on them. This is a working, but not the efficient solution. A good option is to add aggregated data table storing summary counts for the popular queries - countFor7Days, etc. This will improve query performance. But it requires a job that would update the aggregate table every day.
The question is how to implement this job in CloudKit? Is there are such built-in feature, or I need a custom service running somewhere?
My swift app has several places where it updates data stored with SwiftData. In each place I have to remember to add function doSomethingWithTheUpdatedData().
I would like my app to be reactive and call doSomethingWithTheUpdatedData() from a single place opposed to be scattered throughout my app. How to accomplish this?
My iOS Testflight App is crashing immediately after download/start
(on all physical devices)
iOS Console says: SwiftData/DataUtilities.swift:1093: Fatal error: Unable to parse keypath for non-PersistentModel Type
The code is probably it is during
self.modelContainer = try ModelContainer(
for: Model1.self, Model2.self, Model3.self, Model4.self,
configurations:
ModelConfiguration(isStoredInMemoryOnly: isPreview))
modelContainer.mainContext.autosaveEnabled = true
The app runs fine on physical devices in run scheme (debug or release)
I have no clue how to solve this. Any ideas?
I have an app in the app store which is working fine. Some users reported that they have app crashing when they are using iOS 17.4 beta. I could recreate the issue and it is happening when ModelContainer is crerated. This code..
do {
let configuration = ModelConfiguration(for: MyTodo.self, isStoredInMemoryOnly: false)
modelContainer = try ModelContainer(for: MyTodo.self, configurations: configuration)
} catch {
fatalError("Failed to load model container.\(error)")
}
is throwing this error message:
Fatal error: Failed to load model container.SwiftDataError(_error: SwiftData.SwiftDataError._Error.loadIssueModelContainer)
I'm currently facing an interesting issue. A customer is reporting back that my app is crashing on launch for them. I can see the crash logs (using AppCenter for crash management), and the reason the app is crashing seems to be in CoreData:
(Attaching text for seachability, and screenshot for readability):
libsystem_platform.dylib
_platform_memmove$VARIANT$Haswell
CoreData
-[_PFExternalReferenceData initForExternalLocation:safeguardLocation:data:protectionLevel:]
CoreData
-[NSSQLSavePlan _populateRow:fromObject:timestamp:inserted:shouldAddToRowCache:]
CoreData
-[NSSQLSavePlan _createRowsForSave]
CoreData
-[NSSQLSaveChangesRequestContext executePrologue]
CoreData
-[NSSQLCore dispatchRequest:withRetries:]
CoreData
-[NSSQLCore executeRequest:withContext:error:]
CoreData
-[NSPersistentStoreCoordinator executeRequest:withContext:error:]
CoreData
-[NSPersistentStoreCoordinator _routeHeavyweightBlock:]
CoreData
-[NSPersistentStoreCoordinator executeRequest:withContext:error:]
CoreData
-[NSManagedObjectContext save:]
I have never seen that crash before, it's the first time it is appearing since CoreData has been incorporated into the app (in 2016 or so). Any hints on what could possibly be happening? I am unable to provoke the crash on my end, thus debugging is quite interesting.
Hi,
if you have an array of object IDs, with CoreData you can fetch all of the objects for those IDs at once with the right predicate. It would look something like this:
let objectIDs: [NSManagedObjectID] = [id1,id2,id3,id4]
let predicate = NSPredicate(format: "self in %@", objectIDs)
Can something similar be created with a SwiftData predicate? For now I fetch all ids one by one and as you might guess, performance wise this is not great.
Suggestions on what is causing this? Where to look? Could it be related to having a CoreData 'abstract entity' that occurs in two configurations - one configuration for 'public' and one for 'private/shared'?
Hi! I was trying to develop a todo list app. There are two models:
import Foundation
import SwiftData
@Model
class Item {
var id: UUID
var title: String
var detail: String
@Relationship(deleteRule: .cascade, inverse: \SubItem.item) var subitems: [SubItem]
var isCompleted: Bool
var timestamp: Date
init(id: UUID = UUID(), title: String = "", detail: String = "", subitems: [SubItem] = [], isCompleted: Bool = false, timestamp: Date = .now) {
self.id = id
self.title = title
self.detail = detail
self.subitems = subitems
self.isCompleted = isCompleted
self.timestamp = timestamp
}
}
@Model
class SubItem {
var id: UUID
var title: String
var isCompleted: Bool
var item: Item
init(id: UUID = UUID(), title: String = "", isCompleted: Bool = false, item: Item) {
self.id = id
self.title = title
self.isCompleted = isCompleted
self.item = item
}
}
In a component view, I was trying to preload some sample data in the preview:
struct ItemRowView: View {
@Bindable var item: Item
//......
}
#Preview {
let schema = Schema([
Item.self,
SubItem.self
])
let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: true)
let container = try! ModelContainer(for: schema, configurations: [modelConfiguration])
let context = container.mainContext
var item: Item = Item(title: "Item title 1", detail: "")
var subitem1 = SubItem(title: "subitem 4", item: item)
var subitem2 = SubItem(title: "subitem 2", item: item)
context.insert(item)
context.insert(subitem1)
context.insert(subitem2)
return ItemRowView(item: item)
.modelContainer(container)
.padding()
}
However, item.subitems is always empty in this view. What's wrong?
Hi all
In pursuit of adopting widgets in my application, I have transitioned from AppSupport to AppGroup as storage location for Core Data. I have done a migration process/flow that goes as follows and which have been tested multiple times although I have yet to publish the update:
Check if migration has taken place or not
1a. if yes continue to app
1b. If no continue flow
Begin migration process
2a. Backup original store in AppSupport
2b. Migrate store to AppGroup
2c. Migrate userdefaults to AppGroup
2d. Update userdefaults with true for both hasMigratedToAppGroup and hasMigratedUserDefaultsToAppGroup
Is there any tips or stuff to look for that hasn’t been taken in to account? How have you done it previously, and what would be recommended? Also, is there some specific tests to run/over many times get a baseline of how many is succeeding or failing?
Thanks in advance.
Learn how to identify and handle CloudKit throttles.
View Technote TN3162 >
Explore the details inside the synchronization of NSPersistentCloudKitContainer by capturing and analyzing a sysdiagnose.
View Technote TN3163 >
Identify and resolve synchronization issues when working with NSPersistentCloudKitContainer.
View Technote TN3164 >
In the system of iOS17, I store the login information through NSUserDefaults, but after the application is closed, I open it again, and the information stored in NSUserDefaults does not exist. I have not found the specific reason. I did not find this problem in the system before ios 17. This issue only appeared after iOS 17.
I remember long time ago I could click on a button in Xcode to launch a Web page to manage iCloud data. But now I cannot find the button.
I want to make icloud backup using SwiftData in VisionOS and I need to use SwiftData first but I get the following error even though I do the following steps
I followed the steps below
I created a Model
import Foundation
import SwiftData
@Model
class NoteModel {
@Attribute(.unique) var id: UUID
var date:Date
var title:String
var text:String
init(id: UUID = UUID(), date: Date, title: String, text: String) {
self.id = id
self.date = date
self.title = title
self.text = text
}
}
I added modelContainer
WindowGroup(content: {
NoteView()
})
.modelContainer(for: [NoteModel.self])
And I'm making inserts to test
import SwiftUI
import SwiftData
struct NoteView: View {
@Environment(\.modelContext) private var context
var body: some View {
Button(action: { // new Note
let note = NoteModel(date: Date(), title: "New Note", text: "")
context.insert(note)
}, label: {
Image(systemName: "note.text.badge.plus")
.font(.system(size: 24))
.frame(width: 30, height: 30)
.padding(12)
.background(
RoundedRectangle(cornerRadius: 50)
.foregroundStyle(.black.opacity(0.2))
)
})
.buttonStyle(.plain)
.hoverEffectDisabled(true)
}
}
#Preview {
NoteView().modelContainer(for: [NoteModel.self])
}
I get this error even though everything is turned on, how can I solve it?
It works on IOS but I get this error on VisionOS
CoreData: error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _recoverFromPartialError:forStore:inMonitor:]_block_invoke(2726): <NSCloudKitMirroringDelegate: 0x600003b0c700>: Found unknown error as part of a partial failure: <CKError 0x600000cce460: "Permission Failure" (10/2007); server message = "Invalid bundle ID for container"; op = 7FE8CD52A7B2E8FC; uuid = D8D1F2C9-2C01-45B2-BECC-270CA5520D55; container ID = "iCloud.Multitools">
let previewContainer:ModelContainer = {
do {
let config = ModelConfiguration(cloudKitDatabase: .private("iCloud.Multitools"))
let container = try ModelContainer(for: NoteModel.self, configurations: config)
return container
}
catch {
fatalError("Error to create container")
}
}()
Hello! I'm using SwiftData in my app with the @available(iOS 17.0, *) annotation.
It runs perfectly on every simulator runnning on iOS 17.0.1, but I encounter a weird memory error I can't seem to solve on devices running on iOS 17.3.1.
I'm sorta baffled right now. I am trying to wonder how I might detect a updated SQL Store in an older app.
have a baseline app, and create a SQL-based repository
in an updated app, change the model and verify that you can see the updated model version. Using lightweight migration
re-run the older app (which will inherit the newer SQL repository).
YIKES - no error when creating the NSPersistenStoreCoordinator!
Nothing in the metadata to imply the store is newer than the model:
[_persistentStoreCoordinator metadataForPersistentStore:store]
My question: is there any way to detect this condition?
David