I have a SwiftData application that is using CloudKit. If user is on new device. How can I check and fetch data, instead of just waiting for it happen on its own randomly?
For example, I have onboarding which I do not want user to go through again if they already have an active installation.
Seems like SwiftData is severely limited in pretty much every way, specially any useful CloudKit debugging or control functionality.
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
According to my experiments SwiftData does not work with model attributes of primitive type UInt64. More precisely, it crashes in the getter of a UInt64 attribute invoked on an object fetched from the data store.
With Core Data persistent UInt64 attributes are not a problem. Does anyone know whether SwiftData will ever support UInt64?
I am working on a software where we want to add the feature to share the whole database with the other user. Database is iCloud combined with coredata. The other user(s) should be able to edit /delete and even create new objects in the share.
I did this with this code witch directly from sample code
let participants = try await ckConainer.fetchParticipants(matching: [lookupInfo], into: selectedStore)
for participant in participants {
participant.permission = .readWrite
participant.role = .privateUser
share.addParticipant(participant)
}
try await ckConainer.persistUpdatedShare(share, in: selectedStore)
the other user gets invited and I can see this in iCloud database that the other user is invited with status invited.
but the other user never gets a mail or something to accept and join the share. How does the other needs to accept the invitation ?
I work on an app that saves data to the Documents folder in the users iCloud Drive. This uses the iCloud -> iCloud Documents capability with a standard container.
We've noticed an issue where a user will delete the apps data by doing to Settings > {Name} > iCloud > Storage > App Name > select "delete data from iCloud", and then our app can no longer write to or create the Documents folder.
Once that happens, we get this error:
Error Domain=NSCocoaErrorDomain Code=513 "You don't have permission to save the file "Documents" in the folder "iCloud~your~bundle~identifier"." UserInfo={NSFilePath=/private/var/mobile/Library/Mobile Documents/iCloud~your~bundle~identifier/Documents, NSURL=file:///private/var/mobile/Library/Mobile%20Documents/iCloud~your~bundle~identifier/Documents, NSUnderlyingError=0x1102c7ea0 {Error Domain=NSPOSIXErrorDomain Code=13 "Permission denied"}}
This is reproducible using the sample project here https://developer.apple.com/documentation/uikit/synchronizing-documents-in-the-icloud-environment.
Steps to reproduce in that project:
Tap the plus sign in the top right corner to create a new document
Add a document name and tap "Save to Documents"
Go to Settings > {Name} > iCloud > Storage > SimpleiCloudDocument App Name > select "delete data from iCloud"
Reopen the app and repeat steps 1-2
Observe error on MainViewController+Document.swift:59
Deleting and reinstalling the app doesn't seem to help.
Topic:
App & System Services
SubTopic:
iCloud & Data
I've been trying to setup a successful migration, but it keeps failing with this error:
NSCloudKitMirroringDelegate are not reusable and should have a lifecycle tied to a given instance of NSPersistentStore.
I can't find any information about this online. I added breakpoints throughout the code in willMigrate, and it originally failed on this line:
try? context.save()
I removed that, and it still failed. After I reload the app, it doesn't run the migration again and the app loads successfully. I figured since it crashed, it would keep trying, but I guess not. Here's how my migration is setup.
enum MigrationV1ToV2: SchemaMigrationPlan {
static var schemas: [any VersionedSchema.Type] {
[SchemaV1.self, SchemaV2.self]
}
static var stages: [MigrationStage] {
[stage]
}
static let stage = MigrationStage.custom(
fromVersion: SchemaV1.self,
toVersion: SchemaV2.self,
willMigrate: { context in
// Get cycles
let cycles = try? context.fetch(FetchDescriptor<SchemaV1.Cycle>())
if let cycles {
for cycle in cycles {
// Create new recurring objects based on what's in the cycle
for income in cycle.income {
let recurring = SchemaV2.Recurring(name: income.name, frequency: income.frequency, kind: .income)
recurring.addAmount(.init(date: cycle.startDate, amount: income.amount))
context.insert(recurring)
}
for expense in cycle.expenses {
let recurring = SchemaV2.Recurring(name: expense.name, frequency: expense.frequency, kind: .expense)
recurring.addAmount(.init(date: cycle.startDate, amount: expense.amount))
context.insert(recurring)
}
for savings in cycle.savings {
let recurring = SchemaV2.Recurring(name: savings.name, frequency: savings.frequency, kind: .savings)
recurring.addAmount(.init(date: cycle.startDate, amount: savings.amount))
context.insert(recurring)
}
for investment in cycle.investments {
let recurring = SchemaV2.Recurring(name: investment.name, frequency: investment.frequency, kind: .investment)
recurring.addAmount(.init(date: cycle.startDate, amount: investment.amount))
context.insert(recurring)
}
}
//try? context.save()
} else {
print("The cycles were not able to be fetched.")
}
},
didMigrate: { context in
// Get new recurring objects
let newRecurring = try? context.fetch(FetchDescriptor<SchemaV2.Recurring>())
if let newRecurring {
for recurring in newRecurring {
// Get all recurring with the same name and kind
let sameName = newRecurring.filter({ $0.name == recurring.name && $0.kind == recurring.kind })
// Add amount history to recurring object, and then remove matching
for match in sameName {
recurring.amountHistory.append(contentsOf: match.amountHistory)
context.delete(match)
}
}
//try? context.save()
} else {
print("The new recurring objects could not be fetched.")
}
}
)
}
Here's is my modelContainer in the app file. There is a fatal error occurring here that's crashing the app.
var sharedModelContainer: ModelContainer = {
let schema = Schema(versionedSchema: SchemaV2.self)
let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false)
do {
return try ModelContainer(
for: schema,
migrationPlan: MigrationV1ToV2.self,
configurations: [modelConfiguration]
)
} catch {
fatalError("Could not create ModelContainer: \(error)")
}
}()
Does anyone have any suggestions for this?
EDIT:
I found this error in the console that may be relevant.
BUG IN CLIENT OF CLOUDKIT: Registering a handler for a CKScheduler activity identifier that has already been registered (com.apple.coredata.cloudkit.activity.export.8F7A1261-4324-40B4-B041-886DF36FBF0A).
CloudKit setup failed because it couldn't register a handler for the export activity. There is another instance of this persistent store actively syncing with CloudKit in this process.
And here is the fatal error
Fatal error: Could not create ModelContainer: SwiftDataError(_error: SwiftData.SwiftDataError._Error.loadIssueModelContainer, _explanation: nil)
My use case is the following:
Every user of my app can create as an owner a set of items.
These items are private until the owner invites other users to share all of them as participant.
The participants can modify the shared items and/or add other items.
So, sharing is not done related to individual items, but to all items of an owner.
I want to use CoreData & CloudKit to have local copies of private and shared items.
To my understanding, CoreData & CloudKit puts all mirrored items in a special zone „com.apple.coredata.cloudkit.zone“.
So, this zone should be shared, i.e. all items in it.
In the video it is said that NSPersistentCloudKitContainer uses Record Zone Sharing optionally in contrast to hierarchically record sharing using a root record.
But how is this done?
Maybe I can declare zone „com.apple.coredata.cloudkit.zone“ as a shared zone?
Topic:
App & System Services
SubTopic:
iCloud & Data
Tags:
Cloud and Local Storage
UI Frameworks
wwdc21-10015
I am encountering an issue with the UndoManager functionality in a SwiftUI application that integrates SwiftData for persistence. This issue occurs specifically in macOS 14 (Sonoma) but works as expected on macOS 15 (Sequoia).
The focused test app I have prepared for demonstration allows users to create ParentItem objects, and for each ParentItem, users can add multiple ChildItem objects. The undo functionality (via Cmd+Z) is not working as expected in Sonoma. When I try to undo a ChildItem addition, the UndoManager does not revert just the last ChildItem added, but instead removes all ChildItems that were added in that session.
Expected Behavior
On macOS 14 (Sonoma), I expect the UndoManager to undo only the most recent transaction (in this case, a single ChildItem insert), similar to how it functions on macOS 15 (Sequoia). Each ChildItem insertion should be treated as a separate undoable action.
Current Behavior
In macOS Sonoma, pressing Cmd+Z undoes the entire list of ChildItems added to a ParentItem in the current session, rather than just the most recent ChildItem. This appears to be an issue with undo grouping, but I’ve confirmed that no explicit grouping is being used.
Question
Is this an issue with UndoManager in macOS Sonoma, particularly in how it interacts with SwiftData persistence? What changes should I make to ensure that each ChildItem insert is treated as an individual undo action in macOS Sonoma, just as it works in Sequoia?
Any guidance on isolating the issue or recommended workarounds would be appreciated. I would expect that undo actions for each child addition would be treated as separate transactions, not grouped.
Steps Taken to Solve the Problem
I attempted to manually save the model context (modelContext.save()) after each ChildItem insert to ensure proper persistence.
I also verified that UndoManager was not grouping operations explicitly by calling beginUndoGrouping() or endUndoGrouping() myself.
This issue seems to be tied specifically to macOS Sonoma, as it does not occur on macOS Sequoia, where undoing behaves as expected.
Conditions
macOS 14 Sonoma: The issue occurs consistently.
macOS 15 Sequoia: The issue does not occur.
This issue appears to be independent of hardware, as I’ve tested it on multiple machines.
APIs/Features Potentially Involved
UndoManager in a SwiftUI application
SwiftData for persistence (using modelContext.save())
macOS version-specific behavior
Steps to reproduce
Clone test project (https://github.com/Maschina/SwiftDataUndoManagerExample), compile and run
Create a new ParentItem in the app (via plus toolbar button in the sidebar).
Add multiple ChildItems to the ParentItem (via plus toolbar button in the content / middle column of the navigation split view).
Press Cmd+Z to undo the last addition.
Hello,
When attempting to create a CKShare on a personal device linked to a Family iCloud plan (non-primary account holder), the operation fails with a quotaExceeded error. This occurs with the Family plan having 1.5TB available storage space.
This is also causing a data loss for the object(s) that were attempted to be shared.
Details
Account Type: Family iCloud Plan (2TB total storage)
Current Family Usage: 399GB
iCloud Account Usage: 70 GB
Steps to Reproduce:
Have an iCloud account with storage over the 5GB free space limit.
Be on a part of a iCloud Family Plan as the non-primary account holder.
Have storage space available in the Family Plan
Attempt to start a CloudKit Share/Collaboration on the device.
Observe that the CKShare creation fails with a quotaExceeded error.
Expected Behavior:
The CKShare should be successfully created, reflecting the total available storage of the Family plan.
Observed Behavior:
The CKShare fails to be created with quotaExceeded.
Additional Testing
On a test device using an iCloud account with no stored data, the CKShare was created successfully and shared without issue.
Suspected Cause
The CKShare functionality is verifying the personal storage allocation of the iCloud account and failing without checking total available storage provided by the Family plan.
Using SwiftData and this is the simplest example I could boil down:
@Model
final class Item {
var timestamp: Date
var tag: Tag?
init(timestamp: Date) {
self.timestamp = timestamp
}
}
@Model
final class Tag {
var timestamp: Date
init(timestamp: Date) {
self.timestamp = timestamp
}
}
Notice Tag has no reference to Item.
So if I create a bunch of items and set their Tag. Later on I add the ability to delete a Tag. Since I haven't added inverse relationship Item now references a tag that no longer exists so so I get these types of errors:
SwiftData/BackingData.swift:875: Fatal error: This model instance was invalidated because its backing data could no longer be found the store. PersistentIdentifier(id: SwiftData.PersistentIdentifier.ID(url: x-coredata://EEC1D410-F87E-4F1F-B82D-8F2153A0B23C/Tag/p1), implementation: SwiftData.PersistentIdentifierImplementation)
I think I understand now that I just need to add the item reference to Tag and SwiftData will nullify all Item references to that tag when a Tag is deleted.
But, the damage is already done. How can I iterate through all Items that referenced a deleted tag and set them to nil or to a placeholder Tag? Or how can I catch that error and fix it when it comes up?
The crash doesn't occur when loading an Item, only when accessing item.tag?.timestamp, in fact, item.tag?.id is still ok and doesn't crash since it doesn't have to load the backing data.
I've tried things like just looping through all items and setting tag to nil, but saving the model context fails because somewhere in there it still tries to validate the old value.
Thanks!
The NSPersistentCloudKitContainer synchronization between core data and
iCloud was working fine with phone 15.1. Connected a new iPhone iOS 15.5, it gives error:
CoreData: debug: CoreData+CloudKit: -[NSCloudKitMirroringDelegate managedObjectContextSaved:](2504): <NSCloudKitMirroringDelegate: 0x28198c000>: Observed context save: <NSPersistentStoreCoordinator: 0x2809c9420> - <NSManagedObjectContext: 0x2819ad520>
2022-12-05 13:32:28.377000-0600 r2nr[340:6373] [error] error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _importFinishedWithResult:importer:](1245): <PFCloudKitImporter: 0x2837dd740>: Import failed with error:
Error Domain=NSCocoaErrorDomain Code=4864 "*** -[NSKeyedUnarchiver _initForReadingFromData:error:throwLegacyExceptions:]: incomprehensible archive (0x53, 0x6f, 0x6d, 0x65, 0x20, 0x65, 0x78, 0x61)" UserInfo={NSDebugDescription=*** -[NSKeyedUnarchiver _initForReadingFromData:error:throwLegacyExceptions:]: incomprehensible archive (0x53, 0x6f, 0x6d, 0x65, 0x20, 0x65, 0x78, 0x61)}
CoreData: error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _importFinishedWithResult:importer:](1245): <PFCloudKitImporter: 0x2837dd740>: Import failed with error:
Error Domain=NSCocoaErrorDomain Code=4864 "*** -[NSKeyedUnarchiver _initForReadingFromData:error:throwLegacyExceptions:]: incomprehensible archive (0x53, 0x6f, 0x6d, 0x65, 0x20, 0x65, 0x78, 0x61)" UserInfo={NSDebugDescription=*** -[NSKeyedUnarchiver _initForReadingFromData:error:throwLegacyExceptions:]: incomprehensible archive (0x53, 0x6f, 0x6d, 0x65, 0x20, 0x65, 0x78, 0x61)}
I go back and try with my old iPhone iOS 15.1, gives same error.
I am trying to add a custom JSON DataStore and DataStoreConfiguration for SwiftData. Apple kindly provided some sample code in the WWDC24 session, "Create a custom data store with SwiftData", and (once updated for API changes since WWDC) that works fine.
However, when I try to add a relationship between two classes, it fails. Has anyone successfully made a JSONDataStore with a relationship?
Here's my code; firstly the cleaned up code from the WWDC session:
import SwiftData
final class JSONStoreConfiguration: DataStoreConfiguration {
typealias Store = JSONStore
var name: String
var schema: Schema?
var fileURL: URL
init(name: String, schema: Schema? = nil, fileURL: URL) {
self.name = name
self.schema = schema
self.fileURL = fileURL
}
static func == (lhs: JSONStoreConfiguration, rhs: JSONStoreConfiguration) -> Bool {
return lhs.name == rhs.name
}
func hash(into hasher: inout Hasher) {
hasher.combine(name)
}
}
final class JSONStore: DataStore {
typealias Configuration = JSONStoreConfiguration
typealias Snapshot = DefaultSnapshot
var configuration: JSONStoreConfiguration
var name: String
var schema: Schema
var identifier: String
init(_ configuration: JSONStoreConfiguration, migrationPlan: (any SchemaMigrationPlan.Type)?) throws {
self.configuration = configuration
self.name = configuration.name
self.schema = configuration.schema!
self.identifier = configuration.fileURL.lastPathComponent
}
func save(_ request: DataStoreSaveChangesRequest<DefaultSnapshot>) throws -> DataStoreSaveChangesResult<DefaultSnapshot> {
var remappedIdentifiers = [PersistentIdentifier: PersistentIdentifier]()
var serializedData = try read()
for snapshot in request.inserted {
let permanentIdentifier = try PersistentIdentifier.identifier(for: identifier,
entityName: snapshot.persistentIdentifier.entityName,
primaryKey: UUID())
let permanentSnapshot = snapshot.copy(persistentIdentifier: permanentIdentifier)
serializedData[permanentIdentifier] = permanentSnapshot
remappedIdentifiers[snapshot.persistentIdentifier] = permanentIdentifier
}
for snapshot in request.updated {
serializedData[snapshot.persistentIdentifier] = snapshot
}
for snapshot in request.deleted {
serializedData[snapshot.persistentIdentifier] = nil
}
try write(serializedData)
return DataStoreSaveChangesResult<DefaultSnapshot>(for: self.identifier, remappedIdentifiers: remappedIdentifiers)
}
func fetch<T>(_ request: DataStoreFetchRequest<T>) throws -> DataStoreFetchResult<T, DefaultSnapshot> where T : PersistentModel {
if request.descriptor.predicate != nil {
throw DataStoreError.preferInMemoryFilter
} else if request.descriptor.sortBy.count > 0 {
throw DataStoreError.preferInMemorySort
}
let objs = try read()
let snapshots = objs.values.map({ $0 })
return DataStoreFetchResult(descriptor: request.descriptor, fetchedSnapshots: snapshots, relatedSnapshots: objs)
}
func read() throws -> [PersistentIdentifier : DefaultSnapshot] {
if FileManager.default.fileExists(atPath: configuration.fileURL.path(percentEncoded: false)) {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
let data = try decoder.decode([DefaultSnapshot].self, from: try Data(contentsOf: configuration.fileURL))
var result = [PersistentIdentifier: DefaultSnapshot]()
data.forEach { s in
result[s.persistentIdentifier] = s
}
return result
} else {
return [:]
}
}
func write(_ data: [PersistentIdentifier : DefaultSnapshot]) throws {
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .iso8601
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
let jsonData = try encoder.encode(data.values.map({ $0 }))
try jsonData.write(to: configuration.fileURL)
}
}
The data model classes:
import SwiftData
@Model
class Settings {
private(set) var version = 1
@Relationship(deleteRule: .cascade) var hack: Hack? = Hack()
init() {
}
}
@Model
class Hack {
var foo = "Foo"
var bar = 42
init() {
}
}
Container:
lazy var mainContainer: ModelContainer = {
do {
let url = // URL to file
let configuration = JSONStoreConfiguration(name: "Settings", schema: Schema([Settings.self, Hack.self]), fileURL: url)
return try ModelContainer(for: Settings.self, Hack.self, configurations: configuration)
}
catch {
fatalError("Container error: \(error.localizedDescription)")
}
}()
Load function, that saves a new Settings JSON file if there isn't an existing one:
@MainActor func loadSettings() {
let mainContext = mainContainer.mainContext
let descriptor = FetchDescriptor<Settings>()
let settingsArray = try? mainContext.fetch(descriptor)
print("\(settingsArray?.count ?? 0) settings found")
if let settingsArray, let settings = settingsArray.last {
print("Loaded")
} else {
let settings = Settings()
mainContext.insert(settings)
do {
try mainContext.save()
} catch {
print("Error saving settings: \(error)")
}
}
}
The save operation creates a JSON file, which while it isn't a format I would choose, is acceptable, though I notice that the "hack" property (the relationship) doesn't have the correct identifier.
When I run the app again to load the data, I get an error (that there wasn't room to include in this post).
Even if I change Apple's code to not assign a new identifier, so the relationship property and its pointee have the same identifier, it still doesn't load.
Am I doing something obviously wrong, or are relationships not supported in custom data stores?
Hi,
I'm getting a very odd error log in my SwiftData setup for an iOS app. It is implemented to support schema migration. When starting the app, it simply prints the following log twice (seems to be dependent on how many migration steps, I have two steps in my sample code):
CoreData: error: Attempting to retrieve an NSManagedObjectModel version checksum while the model is still editable. This may result in an unstable verison checksum. Add model to NSPersistentStoreCoordinator and try again.
(Yes there is a mistyped word "verison", this is exactly the log)
The code actually fully works. But I have neither CloudKit configured, nor is this app in Production yet. I'm still just developing.
Here is the setup and code to reproduce the issue.
Development mac version: macOS 15.5
XCode version: 16.4
iOS Simulator version: 18.5
Real iPhone version: 18.5
Project name: SwiftDataDebugApp
SwiftDataDebugApp.swift:
import SwiftUI
import SwiftData
@main
struct SwiftDataDebugApp: App {
var sharedModelContainer: ModelContainer = {
let schema = Schema([
Item.self,
])
let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false, allowsSave: true)
do {
return try ModelContainer(for: schema, migrationPlan: ModelMigraitonPlan.self, configurations: [modelConfiguration])
} catch {
fatalError("Could not create ModelContainer: \(error)")
}
}()
var body: some Scene {
WindowGroup {
ContentView()
}
.modelContainer(sharedModelContainer)
}
}
Item.swift:
import Foundation
import SwiftData
typealias Item = ModelSchemaV2_0_0.Item
enum ModelSchemaV1_0_0: VersionedSchema {
static var versionIdentifier = Schema.Version(1, 0, 0)
static var models: [any PersistentModel.Type] {
[Item.self]
}
@Model
final class Item {
var timestamp: Date
init(timestamp: Date) {
self.timestamp = timestamp
}
}
}
enum ModelSchemaV2_0_0: VersionedSchema {
static var versionIdentifier = Schema.Version(2, 0, 0)
static var models: [any PersistentModel.Type] {
[Item.self]
}
@Model
final class Item {
var timestamp: Date
var tags: [Tag] = []
init(timestamp: Date, tags: [Tag]) {
self.timestamp = timestamp
self.tags = tags
}
}
}
enum ModelMigraitonPlan: SchemaMigrationPlan {
static var schemas: [any VersionedSchema.Type] {
[ModelSchemaV1_0_0.self]
}
static var stages: [MigrationStage] {
[migrationV1_0_0toV2_0_0]
}
static let migrationV1_0_0toV2_0_0 = MigrationStage.custom(
fromVersion: ModelSchemaV1_0_0.self,
toVersion: ModelSchemaV2_0_0.self,
willMigrate: nil,
didMigrate: { context in
let items = try context.fetch(FetchDescriptor<ModelSchemaV2_0_0.Item>())
for item in items {
item.tags = Array(repeating: "abc", count: Int.random(in: 0...3)).map({ Tag(value: $0) })
}
try context.save()
}
)
}
Tag.swift:
import Foundation
struct Tag: Codable, Hashable, Comparable {
var value: String
init(value: String) {
self.value = value
}
static func < (lhs: Tag, rhs: Tag) -> Bool {
return lhs.value < rhs.value
}
static func == (lhs: Tag, rhs: Tag) -> Bool {
return lhs.value == rhs.value
}
func hash(into hasher: inout Hasher) {
hasher.combine(value)
}
}
ContentView.swift:
import SwiftUI
import SwiftData
struct ContentView: View {
@Environment(\.modelContext) private var modelContext
@Query private var items: [Item]
var body: some View {
VStack {
List {
ForEach(items) { item in
VStack(alignment: .leading) {
Text(item.timestamp, format: Date.FormatStyle(date: .numeric, time: .standard))
HStack {
ForEach(item.tags, id: \.hashValue) { tag in
Text("\(tag.value)")
}
}
}
}
.onDelete(perform: deleteItems)
}
Button("Add") {
addItem()
}
.padding(.top)
}
}
private func addItem() {
withAnimation {
let newItem = Item(timestamp: Date(), tags: [Tag(value: "Hi")])
modelContext.insert(newItem)
}
do {
try modelContext.save()
} catch {
print("Error saving add: \(error.localizedDescription)")
}
}
private func deleteItems(offsets: IndexSet) {
withAnimation {
for index in offsets {
modelContext.delete(items[index])
}
}
do {
try modelContext.save()
} catch {
print("Error saving delete: \(error.localizedDescription)")
}
}
}
#Preview {
ContentView()
.modelContainer(for: Item.self, inMemory: true)
}
I hope someone can help, couldn't find anything related to this log at all.
Hey all,
This is my first app with Swift, and first app using CloudKit / iCloud - although I have launched other iOS app successfully.
When I created the app, I selected "none" for storage
my bundle identifier looks like this: io.mysite.appname
I have the iCloud capability added, with CloudKit checked, and the container also checked that looks like this: iCloud.io.mysite.appname
Push Notificaitons capability is also added, but there is no configuration.
I have tried automatically managed signing, as well as a manually created provisioning profile..
Every time I build the app onto my device - when I check it out in settings, icloud is not listed. When I go through iCloud into icloud drive, the app is also not listed.
I have cleaned the build many times, deleted and reinstalled the app on my phone many times. I am definitely logged into iCloud etc.
Obviously I have spent plenty of times trying to debug with various LLMs, but we all seem to be at a loss for what I'm missing or doing wrong.
Would love any tips or pointers I may be missing, thank you!
Topic:
App & System Services
SubTopic:
iCloud & Data
Hello Apple Team,
We are looking at developing an iOS feature on our current development that stores user-generated images as CKAssets in the public CloudKit database, with access control enforced by our app’s own logic (not CloudKit Sharing as that has a limit of 100 shares per device). Each story or post is a public record, and users only see content based on buddy relationships handled within the app.
We’d like to confirm that this pattern is consistent with Apple’s best practices for social features. Specifically:
Is it acceptable to store user-uploaded CKAssets in the public CloudKit database, as long as access visibility is enforced by the app?
Are there any performance or quota limitations (e.g., storage, bandwidth, or user sync limits) that apply to CKAssets in the public database when used at scale?
Would CloudKit Sharing be recommended instead, even if we don’t require user-to-user sharing invitations?
For App Review, is this model (public CKAssets + app-enforced access control) compliant with Apple’s data and security expectations?
Are there any caching or bandwidth optimization guidelines for handling image-heavy public CKAsset data in CloudKit?
Thanks again for your time
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..."
If use a SortDescriptor for a model and sort by some attribute from a relationship, in DEBUG mode it all works fine and sorts. However, in release mode, it is an instant crash.
SortDescriptor(.name, order: .reverse) ---- works
SortDescriptor(.assignedUser?.name, order: .reverse) ---- works in debug but crash in release.
What is the issue here, is it that SwiftData just incompetent to do this?
I want to get to a point where I can use a small view with a query for my SwiftData model like this:
@Query
private var currentTrainingCycle: [TrainingCycle]
init(/*currentDate: Date*/) {
_currentTrainingCycle = Query(filter: #Predicate<TrainingCycle> {
$0.numberOfDays > 0
// $0.startDate < currentDate && currentDate < $0.endDate
}, sort: \.startDate)
}
The commented code is where I want to go. In this instance, it'd be created as a lazy var in a viewModel to have it stable (and not constantly re-creating the view). Since it was not working, I thought I could check the same view with a query that does not require any dynamic input. In this case, the numberOfDays never changes after instantiation.
But still, each time the app tries to create this view, the app becomes unresponsive, the CPU usage goes at 196%, memory goes way high and the device heats up quickly.
Am I holding it wrong? How can I have a dynamic predicate on a View in SwiftUI with SwiftData?
I have encountered an issue with a customer’s data access after they migrated to a different iCloud account, and I’m looking for guidance.
The Situation:
The customer was logged into their account on my app, which was associated with a specific iCloud account (iCloud A).
They had all their app data available while using iCloud A.
The customer then switched to a new iCloud account (iCloud B) on the same device, while still using the same app account.
After switching iCloud accounts, their data is no longer visible in the app or my CloudKit dashboard.
My Investigation:
I accessed the customer’s CloudKit data via the CloudKit Console, acting as their iCloud account.
I couldn’t find the private database zone or any of their records when accessing iCloud A through the console.
I don’t believe the data was deleted since actions performed under iCloud B shouldn’t affect data stored in iCloud A.
My Hypothesis:
I suspect that the customer’s old iCloud account (iCloud A) may have downgraded or stopped paying for iCloud storage.
If the iCloud subscription is inactive or expired, could that prevent me from accessing their CloudKit data?
Would renewing the iCloud subscription for iCloud A restore access to the missing data?
Questions:
Does an unpaid or expired iCloud account restrict access to CloudKit records, even if they weren’t deleted?
Would paying for iCloud storage again restore the data previously stored in CloudKit?
Is there any way to recover the customer’s CloudKit data if they are unable to access their old iCloud account?
If anyone has a simpler approach to recovering the customer’s iCloud-stored app data or has experience dealing with iCloud migrations like this, I’d appreciate your insights. Thank you in advance for any advice!
It takes a few seconds, sometimes a few minutes for records to be downloaded back from CloudKit when the user reinstalls the app, which leads users to thinking their data was lost. I would like to know if there’s any way to provide a visual feedback about the current CloudKit sync status so I can let users know their data is being in fact downloaded back to their devices.
Hi,
I am creating (or trying to) my first app using SwiftData - and I have questions :-)
The main question I can't get my head wrapped around is the following:
Let's say I have the sample below...
@Model
class Person {
@Relationship(inverse:\Hat.owner) var hat:Hat
}
@Model
class Hat {
var owner:Person?
}
It looks like I am creating a strong reference cycle between the person and the hat objects? And in fact I am seeing these kinds of reference cycles when I look at the memory debugger.
Many code samples I have seen so far use this type of relationship declaration...
And I am wondering: Am I missing something?
Admittedly I don't find many discussions about memory leaks caused by SwiftData despite the syntax being used in many examples?
So what is the situation? Did Apple just miss to explain that the inverse: declaration causes memory leaks or is there some kind of magic that I should understand?