In a document based SwiftData app for macOS, how do you go about opening a (modal) child window connected to the ModelContainer of the currently open document?
Using .sheet() does not really result in a good UX, as the appearing view lacks the standard window toolbar.
Using a separate WindowGroup with an argument would achieve the desired UX. However, as WindowGroup arguments need to be Hashable and Codable, there is no way to pass a ModelContainer or a ModelContext there:
WindowGroup(id: "myWindowGroup", for: MyWindowGroupArguments.self) { $args in
ViewThatOpensInAWindow(args: args)
}
Is there any other way?
iCloud & Data
RSS for tagLearn how to integrate your app with iCloud and data frameworks for effective data storage
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
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
Topic:
App & System Services
SubTopic:
iCloud & Data
If Cloudkit is enabled, SwiftData @Query operation hangs when the View scenePhase becomes active.
Seems like the more @Query calls you have, the more it hangs.
This has been first documented some time ago, but in typical Apple style, it has not been addressed or even commented on.
https://developer.apple.com/forums/thread/761434
Document based SwiftData apps do not autosave changes to the ModelContext at all. This issue has been around since the first release of this SwiftData feature.
In fact, the Apple WWDC sample project (https://developer.apple.com/documentation/swiftui/building-a-document-based-app-using-swiftdata) does not persist any data in its current state, unless one inserts modelContext.save() calls after every data change.
I have reported this under the feedback ID FB16503154, as it seemed to me that there is no feedback report about the fundamental issue yet.
Other posts related to this problem:
https://forums.developer.apple.com/forums/thread/757172
https://forums.developer.apple.com/forums/thread/768906
https://developer.apple.com/forums/thread/764189
We're in the process of migrating our app to the Swift 6 language mode. I have hit a road block that I cannot wrap my head around, and it concerns Core Data and how we work with NSManagedObject instances.
Greatly simplied, our Core Data stack looks like this:
class CoreDataStack {
private let persistentContainer: NSPersistentContainer
var viewContext: NSManagedObjectContext { persistentContainer.viewContext }
}
For accessing the database, we provide Controller classes such as e.g.
class PersonController {
private let coreDataStack: CoreDataStack
func fetchPerson(byName name: String) async throws -> Person? {
try await coreDataStack.viewContext.perform {
let fetchRequest = NSFetchRequest<Person>()
fetchRequest.predicate = NSPredicate(format: "name == %@", name)
return try fetchRequest.execute().first
}
}
}
Our view controllers use such controllers to fetch objects and populate their UI with it:
class MyViewController: UIViewController {
private let chatController: PersonController
private let ageLabel: UILabel
func populateAgeLabel(name: String) {
Task {
let person = try? await chatController.fetchPerson(byName: name)
ageLabel.text = "\(person?.age ?? 0)"
}
}
}
This works very well, and there are no concurrency problems since the managed objects are fetched from the view context and accessed only in the main thread.
When turning on Swift 6 language mode, however, the compiler complains about the line calling the controller method:
Non-sendable result type 'Person?' cannot be sent from nonisolated context in call to instance method 'fetchPerson(byName:)'
Ok, fair enough, NSManagedObject is not Sendable. No biggie, just add @MainActor to the controller method, so it can be called from view controllers which are also main actor. However, now the compiler shows the same error at the controller method calling viewContext.perform:
Non-sendable result type 'Person?' cannot be sent from nonisolated context in call to instance method 'perform(schedule:_:)'
And now I'm stumped. Does this mean NSManageObject instances cannot even be returned from calls to NSManagedObjectContext.perform? Ever? Even though in this case, @MainActor matches the context's actor isolation (since it's the view context)?
Of course, in this simple example the controller method could just return the age directly, and more complex scenarios could return Sendable data structures that are instantiated inside the perform closure. But is that really the only legal solution? That would mean a huge refactoring challenge for our app, since we use NSManageObject instances fetched from the view context everywhere. That's what the view context is for, right?
tl;dr: is it possible to return NSManagedObject instances fetched from the view context with Swift 6 strict concurrency enabled, and if so how?
I haven't been able to find a definitive answer to this online. Is NSUbiquitousKeyValueStore end-to-end encrypted with Advanced Data Protection turned on? It’s not specifically called out here https://support.apple.com/en-us/102651.
Topic:
App & System Services
SubTopic:
iCloud & Data
I'm testing my app before releasing to testers, and my app (both macOS and iOS) is crashing when I perform one operation, but only in the production build.
I have data that loads from a remote source, and can be periodically updated. There is an option to delete all of that data from the iCloud data store, unless the user has modified a record. Each table has a flag to indicate that (userEdited). Here's the function that is crashing:
func deleteCommonData<T:PersistentModel & SDBuddyModel>(_ type: T.Type) throws {
try modelContext.delete(model: T.self, where: #Predicate<T> { !$0.userEdited })
}
Here's one of the calls that results in a crash:
try modelManager.deleteCommonData(Link.self)
Here's the error from iOS Console:
SwiftData/DataUtilities.swift:85: Fatal error: Couldn't find \Link.<computed 0x0000000104b9d208 (Bool)> on Link with fields [SwiftData.Schema.PropertyMetadata(name: "id", keypath: \Link.<computed 0x0000000104b09b44 (String)>, defaultValue: Optional("54EC6602-CA7C-4EC7-AC06-16E7F2E22DE7"), metadata: nil), SwiftData.Schema.PropertyMetadata(name: "name", keypath: \Link.<computed 0x0000000104b09b84 (String)>, defaultValue: Optional(""), metadata: nil), SwiftData.Schema.PropertyMetadata(name: "url", keypath: \Link.<computed 0x0000000104b09bc4 (String)>, defaultValue: Optional(""), metadata: nil), SwiftData.Schema.PropertyMetadata(name: "desc", keypath: \Link.<computed 0x0000000104b09c04 (String)>, defaultValue: Optional(""), metadata: nil), SwiftData.Schema.PropertyMetadata(name: "userEdited", keypath: \Link.<computed 0x0000000104b09664 (Bool)>, defaultValue: Optional(false), metadata: nil), SwiftData.Schema.PropertyMetadata(name: "modified", keypath: \Link.<computed 0x0000000104b09c44 (Date)>, defaultVal<…>
Here's a fragment of the crash log:
Exception Type: EXC_BREAKPOINT (SIGTRAP)
Exception Codes: 0x0000000000000001, 0x000000019373222c
Termination Reason: Namespace SIGNAL, Code 5, Trace/BPT trap: 5
Terminating Process: exc handler [80543]
Thread 0 Crashed:
0 libswiftCore.dylib 0x19373222c _assertionFailure(_:_:file:line:flags:) + 176
1 SwiftData 0x22a222160 0x22a1ad000 + 479584
2 SwiftData 0x22a2709c0 0x22a1ad000 + 801216
3 SwiftData 0x22a221b08 0x22a1ad000 + 477960
4 SwiftData 0x22a27b0ec 0x22a1ad000 + 844012
5 SwiftData 0x22a27b084 0x22a1ad000 + 843908
6 SwiftData 0x22a28182c 0x22a1ad000 + 870444
7 SwiftData 0x22a2809e8 0x22a1ad000 + 866792
8 SwiftData 0x22a285204 0x22a1ad000 + 885252
9 SwiftData 0x22a281c7c 0x22a1ad000 + 871548
10 SwiftData 0x22a27cf6c 0x22a1ad000 + 851820
11 SwiftData 0x22a27cc48 0x22a1ad000 + 851016
12 SwiftData 0x22a27a6b0 0x22a1ad000 + 841392
13 SwiftData 0x22a285b2c 0x22a1ad000 + 887596
14 SwiftData 0x22a285a10 0x22a1ad000 + 887312
15 SwiftData 0x22a285bcc 0x22a1ad000 + 887756
16 SwiftData 0x22a27cf6c 0x22a1ad000 + 851820
17 SwiftData 0x22a27cc48 0x22a1ad000 + 851016
18 SwiftData 0x22a27a6b0 0x22a1ad000 + 841392
19 SwiftData 0x22a27c0d8 0x22a1ad000 + 848088
20 SwiftData 0x22a27a654 0x22a1ad000 + 841300
21 SwiftData 0x22a1be548 0x22a1ad000 + 70984
22 SwiftData 0x22a1cfd64 0x22a1ad000 + 142692
23 SwiftData 0x22a1b9618 0x22a1ad000 + 50712
24 SwiftData 0x22a1d2e8c 0x22a1ad000 + 155276
25 CoreData 0x187fbb568 thunk for @callee_guaranteed () -> (@out A, @error @owned Error) + 28
26 CoreData 0x187fc2300 partial apply for thunk for @callee_guaranteed () -> (@out A, @error @owned Error) + 24
27 CoreData 0x187fc19c4 closure #1 in closure #1 in NSManagedObjectContext._rethrowsHelper_performAndWait<A>(fn:execute:rescue:) + 192
28 CoreData 0x187fbbda8 thunk for @callee_guaranteed @Sendable () -> () + 28
29 CoreData 0x187fbbdd0 thunk for @escaping @callee_guaranteed @Sendable () -> () + 28
30 CoreData 0x187f663fc developerSubmittedBlockToNSManagedObjectContextPerform + 252
31 libdispatch.dylib 0x180336ac4 _dispatch_client_callout + 16
32 libdispatch.dylib 0x18032c940 _dispatch_lane_barrier_sync_invoke_and_complete + 56
33 CoreData 0x187fd7290 -[NSManagedObjectContext performBlockAndWait:] + 364
34 CoreData 0x187fc1fb8 NSManagedObjectContext.performAndWait<A>(_:) + 544
35 SwiftData 0x22a1b877c 0x22a1ad000 + 46972
36 SwiftData 0x22a1be2a8 0x22a1ad000 + 70312
37 SwiftData 0x22a1c0e34 0x22a1ad000 + 81460
38 SwiftData 0x22a23ea94 0x22a1ad000 + 596628
39 SwiftData 0x22a256828 0x22a1ad000 + 694312
40 Sourdough Buddy 0x104e5dc98 specialized ModelManager.deleteCommonData<A>(_:) + 144 (ModelManager.swift:128) [inlined]
41 Sourdough Buddy 0x104e5dc98 closure #1 in SettingsView.clearStarterData.getter + 876 (SettingsView.swift:243)
It works if I do the following instead:
try modelContext.delete(model: Link.self, where: #Predicate { !$0.userEdited })
Why would the func call work in development, but crash in production? And why does doing the more verbose way work instead?
I think this is a bug.
Thanks
I'm using SwiftData, and I'm using iCloud's CloudKit feature to back up my data.
The problem here is that once you start backing up your data, you can't erase it completely.
Even if the user adds 4 data and erases 4 again, I'm using about 2.5kb.
I don't know how the user using the app will accept this.
I'm trying to provide the user with the ability to erase data at once, what should I do??
Topic:
App & System Services
SubTopic:
iCloud & Data
Tags:
CloudKit
Cloud and Local Storage
iCloud Drive
SwiftData
I'm experiencing a persistent issue with CloudKit sharing in my iOS application. When attempting to present a UICloudSharingController, I receive the error message "Unknown client: ChoreOrganizer" in the console.
App Configuration Details:
App Name: ChoreOrganizer
Bundle ID: com.ProgressByBits.ChoreOrganizer
CloudKit Container ID: iCloud.com.ProgressByBits.ChoreOrganizer
Core Data Model Name: ChoreOrganizer.xcdatamodeld
Core Data Entity: Chore
Error Details:
The error "Unknown client: ChoreOrganizer" occurs when I present the UICloudSharingController
This happens only on the first attempt to share; subsequent attempts during the same app session don't show the error but sharing still doesn't work
All my code executes successfully without errors until UICloudSharingController is presented
Implementation Details:
I'm using NSPersistentCloudKitContainer for Core Data synchronization and UICloudSharingController for sharing. My implementation creates a custom CloudKit zone, saves both a record and a CKShare in that zone, and then presents the sharing controller.
Here's the relevant code:
@MainActor
func presentSharing(from viewController: UIViewController) async throws {
// Create CloudKit container
let container = CKContainer(identifier: containerIdentifier)
let database = container.privateCloudDatabase
// Define custom zone ID
let zoneID = CKRecordZone.ID(zoneName: "SharedChores", ownerName: CKCurrentUserDefaultName)
do {
// Check if zone exists, create if necessary
do {
_ = try await database.recordZone(for: zoneID)
} catch {
let newZone = CKRecordZone(zoneID: zoneID)
_ = try await database.save(newZone)
}
// Create record in custom zone
let recordID = CKRecord.ID(recordName: "SharedChoresRoot", zoneID: zoneID)
let rootRecord = CKRecord(recordType: "ChoreRoot", recordID: recordID)
rootRecord["name"] = "Shared Chores Root" as CKRecordValue
// Create share
let share = CKShare(rootRecord: rootRecord)
share[CKShare.SystemFieldKey.title] = "Shared Tasks" as CKRecordValue
// Save both record and share in same operation
let recordsToSave: [CKRecord] = [rootRecord, share]
_ = try await database.modifyRecords(saving: recordsToSave, deleting: [])
// Present sharing controller
let sharingController = UICloudSharingController(share: share, container: container)
sharingController.delegate = shareDelegate
// Configure popover
if let popover = sharingController.popoverPresentationController {
popover.sourceView = viewController.view
popover.sourceRect = CGRect(
x: viewController.view.bounds.midX,
y: viewController.view.bounds.midY,
width: 1, height: 1
)
popover.permittedArrowDirections = []
}
viewController.present(sharingController, animated: true)
} catch {
throw error
}
}
Steps I've already tried:
Verified correct bundle ID and container ID match in all places (code, entitlements file, Developer Portal)
Added NSUbiquitousContainers configuration to Info.plist
Ensured proper entitlements in the app
Created and configured proper provisioning profiles
Tried both default zone and custom zone for sharing
Various ways of saving the record and share (separate operations, same operation)
Cleaned build folder, deleted derived data, reinstalled the app
Tried on both simulator and physical device
Confirmed CloudKit container exists in CloudKit Dashboard with correct schema
Verified iCloud is properly signed in on test devices
Console Output:
1. Starting sharing process
2. Created CKContainer with ID: iCloud.com.ProgressByBits.ChoreOrganizer
3. Using zone: SharedChores
4. Checking if zone exists
5. Zone exists
7. Created record with ID: <CKRecordID: 0x3033ebd80; recordName=SharedChoresRoot, zoneID=SharedChores:__defaultOwner__>
8. Created share with ID: <CKRecordID: 0x3033ea920; recordName=Share-C4701F43-7591-4436-BBF4-6FA8AF3DF532, zoneID=SharedChores:__defaultOwner__>
9. About to save record and share
10. Records saved successfully
11. Creating UICloudSharingController
12. About to present UICloudSharingController
13. UICloudSharingController presented
Unknown client: ChoreOrganizer
Additional Information:
When accessing the CloudKit Dashboard, I can see that data is being properly synced to the cloud, indicating that the basic CloudKit integration is working. The issue appears to be specific to the sharing functionality.
I would greatly appreciate any insights or solutions to resolve this persistent "Unknown client" error. Thank you for your assistance.
Does anyone have this error and my app can't be searched in the Apple Store
Hi everyone,
Im trying to set up CloudKit for my Unreal Engine 5.4 project but seem to be hitting some roadblocks on how to set up the Record Types.
From my understanding I need to set up a "file" record type with a "contents" asset field - but even with this it doesn't seem to work :(
Any unreal engine devs with some experience on this who could help me out?
Thanks!
I am implementing a custom migration, and facing an issue while implementing a WAL checkpointing.
Here is the code for WAL checkpointing
func forceWALCheckpointingForStore(at storeURL: URL, model: NSManagedObjectModel) throws {
let persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: model)
let options = [NSSQLitePragmasOption: ["journal_mode": "DELETE"]]
let store = try persistentStoreCoordinator.addPersistentStore(type: .sqlite, at: storeURL, options: options)
try persistentStoreCoordinator.remove(store)
}
When the coordinator tries to add the store I am getting the following error
fault: Store opened without NSPersistentHistoryTrackingKey but previously had been opened with NSPersistentHistoryTrackingKey - Forcing into Read Only mode store
My questions are
Is it really necessary to force WAL checkpointing before migration? I am expecting NSMigrationManager to handle it internally. I am assuming this because the migrateStore function asks for the sourceType where I am passing StoreType.sqlite
If checkpointing is required, then how do I address the original issue
Note:
Since my app supports macOS 13, I am not able to use the newly introduced Staged migrations.
There is similar question on Stackoverflow that remains unanswered. https://stackoverflow.com/q/69131577/1311902
I'm developing an app that uses CloudKit synchronization with SwiftData and on visionOS I added an App Settings bundle. I have noticed that sometimes, when the app is open and the user changes a setting from the App Settings bundle, the following fatal error occurs:
SwiftData/BackingData.swift:831: Fatal error: This model instance was destroyed by calling ModelContext.reset and is no longer usable.
The setting is read within the App struct in the visionOS app target using @AppStorage and this value is in turn used to set the passthrough video dimming via the .preferredSurroundingsEffect modifier. The setting allows the user to specify the dimming level as dark, semi dark, or ultra dark.
The fatal error appears to occur intermittently although the first time it was observed was after adding the settings bundle. As such, I suspect there is some connection between those code changes and this fatal error even though they do not directly relate to SwiftData.
Hello,
I'm trying to work on an iPadOS and macOS app that will rely on the document-based system to create some kind of orientation task to follow.
Let say task1.myfile will be a check point regulation from NYC to SF and task2.myfile will be a visit as many key location as you can in SF.
The file represent the specific landmark location and rules of the game.
And once open, I will be able to read KML/GPS file to evaluate their score based with the current task.
But opened GPS files does not have to be stored in the task file itself, it stay alongside.
I wanted to use that scenario to experiment with SwiftData (I'm a long time CoreData user, I even wrote my own WebDAV based persistent store back in the day), and so, mix both on file and in memory persistent store, with distribution based on object class.
With CoreData it would have been possible, but I do not see how to achieve that with SwiftData and DocumentGroup integration.
Any idea how to do that?
Environment
visionOS 26
Xcode 26
Issue
I am experiencing crash when trying to access a [String] from a @Model data, after dismissing an immersiveSpace and opening a WindowGroup.
This crash only occurs when trying to access the [String] property of my Model. It works fine with other properties.
Thread 1: Fatal error: This backing data was detached from a context without resolving attribute faults: PersistentIdentifier(...)
Steps to Reproduce
Open WindowGroup
Dismiss window, open ImmersiveSpace
Dismiss ImmersiveSpace, reopen WindowGroup
Any guidance would be appreciated!
@main
struct MyApp: App {
var body: some Scene {
WindowGroup(id: "main") {
ContentView()
}
.modelContainer(for: [Item.self])
ImmersiveSpace(id: "immersive") {
ImmersiveView()
}
}
}
// In SwiftData model
@Model
class Item {
var title: String = "" // Accessing this property works fine
var tags: [String] = []
@storageRestrictions(accesses: _$backingData, initializes: _tags)
init(initialValue) {
_$backingData.setValue(forKey: \. tags, to: initialValue)
_tags =_ SwiftDataNoType()
}
get {
_$observationRegistrar.access(self, keyPath: \.tags)
**return self getValue(forkey: \.tags)** // Crashes here
}
Are there any differences (either performance or memory considerations) between removing an array of model objects directly using .removeAll() vs using modelContext? Or, are they identical?
Attached below is an example to better illustrate the question (i.e., First Way vs Second Way)
// Model Definition
@Model
class GroupOfPeople {
let groupName: String
@Relationship(deleteRule: .cascade, inverse: \Person.group)
var people: [Person] = []
init() { ... }
}
@Model
class Person {
let name: String
var group: GroupOfPeople?
init() { ... }
}
// First way
struct DemoView: View {
@Query private groups: [GroupOfPeople]
var body: some View {
List(groups) { group in
DetailView(group: group)
}
}
}
struct DetailView: View {
let group: GroupOfPeople
var body: some View {
Button("Delete All Participants") {
group.people.removeAll()
}
}
// Second way
struct DemoView: View {
@Query private groups: [GroupOfPeople]
var body: some View {
List(groups) { group in
DetailView(group: group)
}
}
}
struct DetailView: View {
@Environment(\.modelContext) private var context
let group: GroupOfPeople
var body: some View {
Button("Delete All Participants") {
context.delete(model: Person.self, where: #Predicate { $0.group.name == group.name })
} // assuming group names are unique. more of making a point using modelContext instead
}
我正在使用 Core Data 开发一个 SwiftUI 项目。我的数据模型中有一个名为 AppleUser 的实体,具有以下属性:id (UUID)、name (String)、email (String)、password (String) 和 createdAt (Date)。所有属性都是非可选的。
我使用 Xcode 的自动生成创建了相应的 Core Data 类文件(AppleUser+CoreDataClass.swift 和 AppleUser+CoreDataProperties.swift)。我还有一个 PersistenceController,它使用模型名称 JobLinkModel 初始化 NSPersistentContainer。
当我尝试使用以下方法保存新的 AppleUser 对象时:
让用户 = AppleUser(上下文:viewContext)
user.id = UUID()
user.name = “用户 1”
user.email = “...”
user.password = “密码 1”
user.createdAt = Date()【电子邮件格式正确,但已替换为“...”出于隐私原因】
尝试?viewContext.save()
我在控制台中收到以下错误:核心数据保存失败:Foundation._GenericObjCError.nilError, [:]
用户快照: [“id”: ..., “name”: “User1”, “email”: “...”, “password”: “...”, “createdAt”: ...]
所有字段都有有效值,核心数据模型似乎正确。我还尝试过:
• 检查 NSPersistentContainer(name:) 中的模型名称是否与 .xcdatamodeld 文件 (JobLinkModel) 匹配
• 确保正确设置 AppleUser 实体类、模块和 Codegen(类定义、当前产品模块)
• 删除重复或旧的 AppleUser 类文件
• 清理 Xcode 构建文件夹并从模拟器中删除应用程序
• 对上下文使用 @Environment(.managedObjectContext)
尽管如此,在保存新的 AppleUser 对象时,我仍然会收到 _GenericObjCError.nilError。
我想了解:
为什么即使所有字段都不是零且正确分配,核心数据也无法保存?
这可能是由于一些残留的旧类文件引起的,还是我缺少设置中的其他内容?
我应该采取哪些步骤来确保 Core Data 正确识别 AppleUser 实体并允许保存?
任何帮助或指导将不胜感激。
After the significant issues with the ModelActor in iOS 18, it seemed like the ModelActor became more stable with iOS 18.1 and macOS 15.1.
However, I’m still encountering problems and crashes. I wanted to ask if these issues are related to my persistence layer architecture or if they’re still inherent to the ModelActor itself.
I’ve generally followed the blog posts:
https://fatbobman.com/en/posts/practical-swiftdata-building-swiftui-applications-with-modern-approaches/
and
https://brightdigit.com/tutorials/swiftdata-modelactor/
and aim to achieve the following:
I have a single DataProvider that holds the ModelContainer and uses it to configure and initialize a single DataHandler. These are created once at app launch and injected into the SwiftUI view hierarchy as EnvironmentObjects. Since I need to access the SwiftData models not only in SwiftUI but also indirectly in ViewModels or UIKit views, all read operations on the models should go through the DataProvider (and its MainContext), while all other CRUD operations are handled centrally via the single DataHandler (executed within a single ModelActor).
Additionally, I want to monitor the entire container using another ModelActor, initialized in the DataProvider, which tracks changes to objects using TransactionHistory.
I’ve managed to implement this to some extent, but I’m facing two main issues:
1. ModelActor and Main Actor Requirement
The ModelActor only updates SwiftUI views when initialized via the maincontext of the ModelContainer and therefore runs on the Main Actor. It would be ideal for this to work in the background, but the issue with the ModelActor that existed previously doesn’t seem to have been resolved in iOS 18.1/macOS 15.1—am I wrong about this?
2. Frequent Crashes (more severe)
Crashes occur, especially when multiple windows on macOS or on iPad access the same DataHandler to update models. This often leads to crashes during read operations on models by a SwiftUI view (but not only), with logs like:
error: the replacement path doesn't exist: "/var/folders/gs/8rwdjczj225d1pj046w3d97c0000gn/T/swift-generated-sources/@__swiftmacro_12SwiftDataTSI3TagC4uuID18_PersistedPropertyfMa_.swift"
Can't show file for stack frame : <DBGLLDBStackFrame: 0x34d28e170> - stackNumber:1 - name:Tag.uuID.getter. The file path does not exist on the file system: /var/folders/gs/8rwdjczj225d1pj046w3d97c0000gn/T/swift-generated-sources/@__swiftmacro_12SwiftDataTSI3TagC4uuID18_PersistedPropertyfMa_.swift
This error usually happens when there are multiple concurrent accesses to the DataHandler/ModelActor. However, crashes also occur sporadically during frequent accesses from a single view with an error like "the replacement path doesn't exist."
It also seems like having multiple ModelActors, as in this case (one for observation and one for data changes), causes interference and instability. The app appears to crash less frequently when the observer is not initialized, but I can’t verify this—it might just be a coincidence.
My Question:
Am I fundamentally doing something wrong with the ModelActors or the architecture of my persistence layer?
I'm working on a macOS app with a Safari web extension. I'm trying to share a SwiftData model between devices using CloudKit synchronization. I am able to get synchronization in the main app on the same device, CloudKit sync works correctly — changes appear in the CloudKit Dashboard under com.apple.coredata.cloudkit.zone.
However, in the Safari App Extension, data is saved locally and persists across launches, but never syncs to CloudKit.
I have followed the recommended practices for configuring the App Group and entitlements, but the issue persists.
Questions:
Is there an official limitation preventing Safari App Extensions from connecting to the CloudKit daemon (cloudd)?
If not, what entitlements or configuration changes are required for a Safari App Extension to successfully sync with CloudKit?
Is the xpc_error=159 from bootstrap_look_up() a known sandbox restriction for this extension type?
Any guidance from Apple engineers or others who have successfully used CloudKit from a Safari App Extension would be appreciated.
What I’ve confirmed:
The extension’s .entitlements includes:
com.apple.security.app-sandbox
com.apple.developer.icloud-services
CloudKit
com.apple.developer.icloud-container-identifiers
iCloud.dev.example.myapp
Same iCloud container ID for both app and extension
CloudKit container exists and is initialized in CloudKit Console
Running in :Sandbox environment during development
Database name in SwiftData matches container identifier (without the iCloud. prefix)
The extension’s codesign output shows correct entitlements
App Group is configured (although in this case, extension and app use separate stores intentionally)
Observed behavior in Console.app logs:
CloudKit sync engine initializes in the extension
XPC activities are registered for import/export:
_xpc_activity_register: com.apple.coredata.cloudkit.activity.export.
xpc_activity_set_criteria: ... import.
Then a bootstrap lookup fails:
failed to do a bootstrap look-up: xpc_error=[159: Unknown error: 159]
CloudKit daemon connection error:
CKErrorDomain Code=6 "Error connecting to CloudKit daemon"
NSCocoaErrorDomain Code=4099
There is no “Will attempt to upload transactions” or “Upload succeeded” logs are ever seen.
Symptoms
When the extension is run, I see logs like the following in Console.app:
[0x13e215820] failed to do a bootstrap look-up: xpc_error=[159: Unknown error: 159]
CoreData+CloudKit: -[PFCloudKitSetupAssistant _checkAccountStatus:]_block_invoke(342): Fetched account info for store : (null)
Error Domain=CKErrorDomain Code=6 "Error connecting to CloudKit daemon. This could happen for many reasons..."
Hi,
I'm implementing iCloud backup functionality in my web application using CloudKit JS, but I'm running into some issues. I'd appreciate any help you can provide.
Issue:
The iCloud backup feature isn't working properly in our web app. I believe I've correctly set up the Apple Developer Program registration and API token generation. While a demo implementation works perfectly with iCloud backup, our app implementation is failing.
Specifically:
"Sign in with Apple" succeeds
However, ck.getDefaultContainer().setupAuth() returns null
In the working demo, setupAuth() returns a proper value
Even after logging in through the redirect URL provided in the "421 Misdirected Request" error response and executing setupAuth(), it still returns null
I've essentially copied the working demo code directly, so I suspect the issue might be related to token generation, permissions, or account configuration.
Questions:
Could you provide detailed step-by-step instructions for implementing iCloud backup in a web application? I've noticed there are configuration items in the Developer Console and Certificates console, so I may have missed something in one of these areas.
Based on the symptoms described, what are the possible causes for setupAuth() returning null in CloudKit JS? Could configuration issues be indirectly causing this, or is it more likely a timing issue or SDK coding problem?
Specifically regarding the 421 error and redirect flow - is there something in the configuration that could cause setupAuth() to return null even after successful authentication through the redirect?
Thanks in advance for your help!
Topic:
App & System Services
SubTopic:
iCloud & Data