iCloud & Data

RSS for tag

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

CloudKit Documentation

Posts under iCloud & Data subtopic

Post

Replies

Boosts

Views

Activity

NSCocoaErrorDomain Code=513 after user delete's
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.
2
0
61
3w
CloudKit sign in error in normal tab
Hi, I'm trying to sign in with Apple CloudKit. I'm using the following code: 'use client'; import { CLOUDKIT_CONSTANTS } from '@/constants/cloudkit'; import { setCloudKitConfigured } from '@/lib/cloudkitSingleton'; import { CloudKitStatic } from '@/types/cloudkit'; import Script from 'next/script'; declare global { interface Window { CloudKit: CloudKitStatic; } } export default function Home() { const initializeCloudKit = async () => { console.info('⭐️ initializeCloudKit - start'); // 古い認証情報を削除 try { // LocalStorageから古い認証情報を削除 const keysToRemove = []; for (let i = 0; i < localStorage.length; i++) { const key = localStorage.key(i); if (key && (key.includes('cloudkit') || key.includes('CloudKit'))) { keysToRemove.push(key); } } keysToRemove.forEach(key => localStorage.removeItem(key)); // SessionStorageからも削除 const sessionKeysToRemove = []; for (let i = 0; i < sessionStorage.length; i++) { const key = sessionStorage.key(i); if (key && (key.includes('cloudkit') || key.includes('CloudKit'))) { sessionKeysToRemove.push(key); } } sessionKeysToRemove.forEach(key => sessionStorage.removeItem(key)); console.log('古い認証情報を削除しました'); } catch (cleanupError) { console.warn('認証情報のクリーンアップ中にエラー:', cleanupError); } try { const cloudKit = window.CloudKit.configure({ containers: [ { containerIdentifier: 'XXXXXX', apiTokenAuth: { apiToken: 'XXXX-XXXX-XXXX-XXXX-XXXX-XXXX-XXXX-XXXX', persist: false, signInButton: { id: 'cloudkit-sign-in-button', theme: 'black', }, signOutButton: { id: 'cloudkit-sign-out-button', theme: 'black', }, }, environment: 'development', }, ], }); console.info('⭐️ cloudKit', cloudKit); setCloudKitConfigured(true); const container = cloudKit.getDefaultContainer(); console.info('⭐️ CloudKit configured, setting up auth...'); // 初期認証状態をチェック try { const initialUser = await container.setUpAuth(); console.info('⭐️ setUpAuth result:', initialUser); } catch (authError) { console.info('⭐️ setUpAuth error (expected for unauthenticated):', authError); } // CloudKitの標準コールバックも併用(念のため) try { container.whenUserSignsIn().then((userInfo: any) => { console.info('⭐️ CALLBACK: whenUserSignsIn fired!', userInfo); }); container.whenUserSignsOut().then(() => { console.info('⭐️ CALLBACK: whenUserSignsOut fired!'); }); } catch (callbackError) { console.info('⭐️ Callback setup error (non-critical):', callbackError); } console.info('⭐️ initializeCloudKit - completed'); } catch (error) { console.error('⭐️ Critical CloudKit initialization error:', error); } }; return ( <> <Script src="https://cdn.apple-cloudkit.com/ck/2/cloudkit.js" strategy="afterInteractive" onLoad={() => { initializeCloudKit(); }} onError={error => { console.error('⭐️ CloudKit initialization error:', error); }} /> <div id="cloudkit-sign-in-button" /> <div id="cloudkit-sign-out-button" /> </> ); } In Chrome secret tab, I can sign in successfully. But in Chrome normal tab, I can't sign in. In normal tab, following error occurs on sign in button click: cloudkit.js:14 Uncaught (in promise) Error: UNKNOWN_ERROR cloudkit.js:14 GET https://api.apple-cloudkit.com/database/1/XXXXXX/XXXXXX/public/users/caller?ckjsBuildVersion=2420ProjectDev22&ckjsVersion=2.6.4&clientId=XXXXX-XXXXXXX-XXXX-XXXXX& ckAPIToken=XXXX-XXXX-XXXX-XXXX-XXXX-XXXX-XXXX-XXXX 421 (Misdirected Request) I think, cloudkit instance has re-initialized when I click the sign in button only in normal tab. So I can't sign in. Do you have any idea what might be causing the error ? Thanks in advance for your help!
0
0
79
4w
Safari App Extension fails to connect to CloudKit daemon (cloudd) with XPC communication errors -- CKErrorDomain Code=6 / NSCocoaErrorDomain Code=4099 – Unable to connect to CloudKit daemon
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..."
2
0
62
Aug ’25
Are data in an iCloud NSUbiquitousKeyValueStore directly available at app launch on another device?
Hello, I'm planning to had an onboarding to one of my apps. I am thinking about a way for a user to not see the onboarding again if he installs the app on another device. So for example, the user completes the onboarding on its iPhone, then downloads the app on its iPad and launch it, he doesn't see the onboarding a second time. I thought about using iCloud NSUbiquitousKeyValueStored to store the onboarding completion state. But I'm not sure when the data is synced to the other device logged into the same Apple account: Immediately even if the app is not installed on the other device (independent from the app, only iCloud thing)? At the same time as the app install on the other device? After the app is first launched on the other device? Of course synchronisation will depend on the Internet connection, speed, etc. so the app should handle the case where the data is not here but what would be the best case scenario? Thank you, Axel
1
0
49
Aug ’25
CloudKit it writes to development container, not Production
I have an app that I signed and distribute between some internal testflight users. Potentially I want to invite some 'Public' beta testers which don't need to validate (_World have read rights in the public database) Question: Do I need to have a working public CloudKit , when users are invited through TestFlight, or are they going to test on the development container? I understand that when I invite beta-tester without authorization (external testers) they cannot access the developer container, so therefore I need to have the production CloudKit container up and running. I have tried to populate the public production container, but for whatever reason my upload app still goes to the development container. I have archived the app, and tried, but no luck. I let xcode manage my certificates/profiles. but what do I need to change to be able to use my upload file to upload the production container, instead of the development. I tried: init() { container = CKContainer(identifier: "iCloud.com.xxxx.xxxx") publicDB = container.publicCloudDatabase I got no error in the console, but data is always populated to the development database, instead the production. I tried to create a provisioning profile, but for some reason Xcode doesn't like it. Tried to create one a different provisioning profile manual through the developer portal, for the app. but xcode doesn't want to use that, and mentions that the requirement are already in place. What can I check/do to solve this.
1
0
67
Aug ’25
Errors reading not-yet-sync'd iCloud files get cached
I have an app which uses ubiquitous containers and files in them to share data between devices. It's a bit unusual in that it indexes files in directories the user grants access to, which may or may not exist on a second device - those files are identified by SHA-1 hash. So a second device scanning before iCloud data has fully sync'd can create duplicate references which lead to an unpleasant user experience. To solve this, I store a small binary index in the root of the ubiquitous file container of the shared data, containing all of the known hashes, and as the user proceeds through the onboarding process, a background thread is attempting to "prime" the ubiquitous container by calling FileManager.default.startDownloadingUbiquitousItemAt() for each expected folder and file in a sane order. This likely creates a situation not anticipated by the iOS/iCloud integration's design, as it means my app has a sort of precognition of files it should not yet know about. In the common case, it works, but there is a corner case where iCloud sync has just begun, and very, very little metadata is available (the common case, however, in an emulator), in which two issues come up: I/O may hang indefinitely, trying to read a file as it is arriving. This one I can work around by running the I/O in a thread created with the POSIX pthread_create and using pthread_cancel to kill it after a timeout. Attempts to call FileManager.default.startDownloadingUbiquitousItemAt() fails with an error Error Domain=NSCocoaErrorDomain Code=257 "The file couldn’t be opened because you don’t have permission to view it.". The permissions aspect of it is nonsense, but I can believe there's no applicable "sort of exists, sort of doesn't" error code to use and someone punted. The problem is that this same error will be thrown on any attempt to access that file for the life of the application - a restart is required to make it usable. Clearly, the error or the hallucinated permission failure is cached somewhere in the bowels of iOS's FileManager. I was hoping startAccessingSecurityScopedResource() would allow me to bypass such a cache, as it does with URL.resourceValues() returning stale file sizes and last modified times. But it does not. Is there some way to clear this state without popping up a UI with an Exit button (not exactly the desired iOS user experience)?
1
0
53
Aug ’25
iCloud Drive Implementation Issue in My App
Hi, I'm having trouble implementing iCloud Drive in my app. I've already taken the obvious steps, including enabling iCloud Documents in Xcode and selecting a container. This container is correctly specified in my code, and in theory, everything should work. The data generated by my app should be saved to iCloud Drive in addition to local storage. The data does get stored in the Files app, but the automatic syncing to iCloud Drive doesn’t work as expected. I’ve also considered updating my .entitlements file. Since I’m at a loss, I’m reaching out for help maybe I’ve overlooked something important that's causing it not to work. If anyone has an idea, please let me know. Thanks in advance!
1
0
86
Aug ’25
Bundling app with our own SQLite
Hey there, Can we bundle our app with our own version of SQLite with extensions that we want. From what I've seen, we aren't allowed to add extensions to the built in IOS SQLite, so would this be the only way to use extensions. I ask this because I want to use the spell fix extension. I couldn't find a lot of people talking about adding SQLite extensions. Thank you!
5
0
118
Aug ’25
Troubleshooting CloudKit JS iCloud Backup: setupAuth() Returns Null After Sign in with Apple
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!
1
0
62
Jul ’25
Can't get CloudKit to load data on cloud
The app works on a local db but when I try to make it work with iCloud I get errors that I don't understand. CoreData+CloudKit: -[NSCloudKitMirroringDelegate _performSetupRequest:]_block_invoke(1247): <NSCloudKitMirroringDelegate: 0x10664c200>: Failed to set up CloudKit integration for store: <NSSQLCore: 0x106688140> (URL: file:///var/mobile/Containers/Data/Application/20EF350F-F0FA-4132-97DA-61B60AADB101/Library/Application%20Support/default.store) <CKError 0x109430e40: "Partial Failure" (2/1011); "Failed to modify some record zones"; uuid = 82ED152A-D015-414D-BB79-AF36E5AF4A8B; container ID = "iCloud.se.Grindegard.MinaRecept"; partial errors: { com.apple.coredata.cloudkit.zone:defaultOwner = <CKError 0x109431230: "Permission Failure" (10/2007); server message = "Invalid bundle ID for container"; op = E56A3CDA393641F8; uuid = 82ED152A-D015-414D-BB79-AF36E5AF4A8B> }> what can be wrong?
3
0
40
Jul ’25
CloudKit Sharing Not Working with Other Apple IDs (SwiftData + SwiftUI)
Hi everyone, I’m currently developing a SwiftUI app that uses SwiftData with CloudKit sharing enabled. The app works fine on my own Apple ID, and local syncing with iCloud is functioning correctly — but sharing with other Apple IDs consistently fails. Setup: SwiftUI + SwiftData using a ModelContainer with .shared configuration Sharing UI is handled via UICloudSharingController iCloud container: iCloud.com.de.SkerskiDev.FoodGuard Proper entitlements enabled (com.apple.developer.icloud-services, CloudKit, com.apple.developer.coredata.cloudkit.containers, etc.) Automatic provisioning profiles created by Xcode Error:<CKError 0x1143a2be0: "Bad Container" (5/1014); "Couldn't get container configuration from the server for container iCloud.com.de.SkerskiDev.FoodGuard"> What I’ve tried: Verified the iCloud container is correctly created and enabled in the Apple Developer portal Checked bundle identifier and container settings Rebuilt and reinstalled the app Ensured correct iCloud entitlements and signing capabilities Questions: Why does CloudKit reject the container for sharing while local syncing works fine? Are there known issues with SwiftData .shared containers and multi-user sharing? Are additional steps required (App Store Connect, privacy settings) to allow sharing with other Apple IDs? Any advice, experience, or example projects would be greatly appreciated. 🙏 Thanks! Sebastian
4
0
129
Jul ’25
CloudKit: Records not indexing
Since publishing new record types to my CloudKit schema in production, a previously unchanged record type has stopped indexing new records. While records of this type are successfully saved without errors, they are not returned in query results—they can only be accessed directly via their recordName. This issue occurs exclusively in the Production environment, both in the CloudKit Console and our iOS app. The problem began on July 21, 2025, and continues to persist. The issue affects only new records of this specific record type; all other types are indexing and querying as expected. The affected record's fields are properly configured with the appropriate index types (e.g., QUERYABLE) and have been not been modified prior to publishing the schema. With this, are there any steps I should take to restore indexing functionality for this record type in Production? There have been new records inserted, and I would prefer to not have to reset the production database, if possible.
4
1
165
Jul ’25
Change to SwiftData ModelContainer causing crashes
I have some models in my app: [SDPlanBrief.self, SDAirport.self, SDChart.self, SDIndividualRunwayAirport.self, SDLocationBrief.self] SDLocationBrief has a @Relationship with SDChart When I went live with my app I didn't have a versioned schema, but quickly had to change that as I needed to add items to my SDPlanBrief Model. The first versioned schema I made included only the model that I had made a change to. static var models: [any PersistentModel.Type] { [SDPlanBrief.self] } I had made zero changes to my model container and the whole time, and it was working fine. The migration worked well and this is what I was using: .modelContainer(for: [SDAirport.self, SDIndividualRunwayAirport.self, SDLocationBrief.self, SDChart.self, SDPlanBrief.self]) I then saw that to do this all properly, I should actually include ALL of my @Models in the versioned schema: enum AllSwiftDataSchemaV3: VersionedSchema { static var models: [any PersistentModel.Type] { [SDPlanBrief.self, SDAirport.self, SDChart.self, SDIndividualRunwayAirport.self, SDLocationBrief.self] } static var versionIdentifier: Schema.Version = .init(2, 0, 0) } extension AllSwiftDataSchemaV3 { @Model class SDPlanBrief { var destination: String etc... init(destination: String, etc...) { self.destination = destination etc... } } @Model class SDAirport { var catABMinima: String etc... init(catABMinima: String etc...) { self.catABMinima = catABMinima etc... } } @Model class SDChart: Identifiable { var key: String etc... var brief: SDLocationBrief? // @Relationship with SDChart init(key: String etc...) { self.key = key etc... } } @Model class SDIndividualRunwayAirport { var icaoCode: String etc... init(icaoCode: String etc...) { self.icaoCode = icaoCode etc... } } @Model class SDLocationBrief: Identifiable { var briefString: String etc... @Relationship(deleteRule: .cascade, inverse: \SDChart.brief) var chartsArray = [SDChart]() init( briefString: String, etc... chartsArray: [SDChart] = [] ) { self.briefString = briefString etc... self.chartsArray = chartsArray } } } This is ALL my models in here btw. I saw also that modelContainer needed updating to work better for versioned schemas. I changed my modelContainer to look like this: actor ModelContainerActor { @MainActor static func container() -> ModelContainer { let schema = Schema( versionedSchema: AllSwiftDataSchemaV3.self ) let configuration = ModelConfiguration() let container = try! ModelContainer( for: schema, migrationPlan: PlanBriefMigrationPlan.self, configurations: configuration ) return container } } and I am passing in like so: .modelContainer(ModelContainerActor.container()) Each time I run the app now, I suddenly get this message a few times in a row: 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. I typealias all of these models too for the most recent V3 version eg: typealias SDPlanBrief = AllSwiftDataSchemaV3.SDPlanBrief Can someone see if I am doing something wrong here? It seems my TestFlight users are experiencing a crash every now and then when certain views load (I assume when accessing @Query objects). Seems its more so when a view loads quickly, like when removing a subscription view where the data may not have had time to load??? Can someone please have a look and help me out.
6
0
203
Jul ’25
QuotaExceeded error for RecordDelete operation
In the CloudKit logs I see logs that suggest users getting QUOTA_EXCEEDED error for RecordDelete operations. { "time":"21/07/2025, 7:57:46 UTC" "database":"PRIVATE" "zone":"***" "userId":"***" "operationId":"***" "operationGroupName":"2.3.3(185)" "operationType":"RecordDelete" "platform":"iPhone" "clientOS":"iOS;18.5" "overallStatus":"USER_ERROR" "error":"QUOTA_EXCEEDED" "requestId":"***" "executionTimeMs":"177" "interfaceType":"NATIVE" "recordInsertBytes":54352 "recordInsertCount":40 "returnedRecordTypes":"_pcs_data" } I'm confused as to what this means? Why would a RecordDelete operation have recordInsertBytes? I'd expect a RecordDelete operation to never fail on quotaExceeded and how would I handle that in the app?
1
0
48
Jul ’25
SwiftData SortDescriptor Limitation...
I built a SwiftData App that relies on CloudKit to synchronize data across devices. That means all model relationships must be expressed as Optional. That’s fine, but there is a limitation in using Optional’s in SwiftData SortDescriptors (Crashes App) That means I can’t apply a SortDescriptor to ModelA using some property value in ModelB (even if ModelB must exist) I tried using a computed property in ModelA that referred to the property in ModelB, BUT THIS DOESN”T WORK EITHER! Am I stuck storing redundant data In ModelA just to sort ModelA as I would like???
4
0
145
Jul ’25
SwiftData error: Attempting to retrieve an NSManagedObjectModel version checksum while the model is still editable
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.
2
0
85
Jul ’25
icloud capability not working?
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!
2
0
129
Jul ’25
Extending @Model with custom macros
I am trying to extend my PersistedModels like so: @Versioned(3) @Model class MyType { var name: String init() { name = "hello" } } but it seems that SwiftData's@Model macro is unable to read the properties added by my @Versioned macro. I have tried changing the order and it ignores them regardless. version is not added to schemaMetadata and version needs to be persisted. I was planning on using this approach to add multiple capabilities to my model types. Is this possible to do with macros? VersionedMacro /// A macro that automatically implements VersionedModel protocol public struct VersionedMacro: MemberMacro, ExtensionMacro { // Member macro to add the stored property directly to the type public static func expansion( of node: AttributeSyntax, providingMembersOf declaration: some DeclGroupSyntax, in context: some MacroExpansionContext ) throws -> [DeclSyntax] { guard let argumentList = node.arguments?.as(LabeledExprListSyntax.self), let firstArgument = argumentList.first?.expression else { throw MacroExpansionErrorMessage("@Versioned requires a version number, e.g. @Versioned(3)") } let versionValue = firstArgument.description.trimmingCharacters(in: .whitespaces) // Add the stored property with the version value return [ "public private(set) var version: Int = \(raw: versionValue)" ] } // Extension macro to add static property public static func expansion( of node: SwiftSyntax.AttributeSyntax, attachedTo declaration: some SwiftSyntax.DeclGroupSyntax, providingExtensionsOf type: some SwiftSyntax.TypeSyntaxProtocol, conformingTo protocols: [SwiftSyntax.TypeSyntax], in context: some SwiftSyntaxMacros.MacroExpansionContext ) throws -> [SwiftSyntax.ExtensionDeclSyntax] { guard let argumentList = node.arguments?.as(LabeledExprListSyntax.self), let firstArgument = argumentList.first?.expression else { throw MacroExpansionErrorMessage("@Versioned requires a version number, e.g. @Versioned(3)") } let versionValue = firstArgument.description.trimmingCharacters(in: .whitespaces) // We need to explicitly add the conformance in the extension let ext = try ExtensionDeclSyntax("extension \(type): VersionedModel {}") .with(\.memberBlock.members, MemberBlockItemListSyntax { MemberBlockItemSyntax(decl: DeclSyntax( "public static var version: Int { \(raw: versionValue) }" )) }) return [ext] } } VersionedModel public protocol VersionedModel: PersistentModel { /// The version of this particular instance var version: Int { get } /// The type's current version static var version: Int { get } } Macro Expansion:
1
0
364
Jul ’25