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

@Query with Set
How do I filter data using @Query with a Set of DateComponents? I successfully saved multiple dates using a MultiDatePicker in AddView.swift. In ListView.swift, I want to retrieve all records for the current or today’s date. There are hundreds of examples using @Query with strings and dates, but I haven’t found an example of @Query using a Set of DateComponents Nothing will compile and after hundreds and hundreds of attempts, my hair is turning gray. Please, please, please help me. For example, if the current date is Tuesday, March 4 205, then I want to retrieve both records. Since both records contain Tuesday, March 4, then retrieve both records. Sorting works fine because the order by clause uses period which is a Double. Unfortunately, my syntax is incorrect and I don’t know the correct predicate syntax for @Query and a Set of DateComponents. Class Planner.swift file import SwiftUI import SwiftData 
 @Model class Planner { //var id: UUID = UUID() var grade: Double = 4.0 var kumi: Double = 4.0 var period: Double = 1.0 var dates: Set<DateComponents> = [] init( grade: Double = 4.0, kumi: Double = 4.0, period: Double = 1.0, dates: Set<DateComponents> = [] ) { self.grade = grade self.kumi = kumi self.period = period self.dates = dates 
 } } @Query Model snippet of code does not work The compile error is to use a Set of DateComponents, not just DateComponents. @Query(filter: #Predicate<Planner> { $0.dates = DateComponents(calendar: Calendar.current, year: 2025, month: 3, day: 4)}, sort: [SortDescriptor(\Planner.period)]) var planner: [Planner] ListView.swift image EditView.swift for record #1 DB Browser for SQLlite: record #1 (March 6, 2025 and March 4, 2025) 
 
 [{"isLeapMonth":false,"year":2025,"day":6,"month":3,"calendar":{"identifier":"gregorian","minimumDaysInFirstWeek":1,"current":1,"locale":{"identifier":"en_JP","current":1},"firstWeekday":1,"timeZone":{"identifier":"Asia\/Tokyo"}},"era":1},{"month":3,"year":2025,"day":4,"isLeapMonth":false,"era":1,"calendar":{"locale":{"identifier":"en_JP","current":1},"timeZone":{"identifier":"Asia\/Tokyo"},"current":1,"identifier":"gregorian","firstWeekday":1,"minimumDaysInFirstWeek":1}}]
 EditView.swift for record #2 DB Browser for SQLlite: record #2 (March 3, 2025 and March 4, 2025) 
 [{"calendar":{"minimumDaysInFirstWeek":1,"locale":{"current":1,"identifier":"en_JP"},"timeZone":{"identifier":"Asia\/Tokyo"},"firstWeekday":1,"current":1,"identifier":"gregorian"},"month":3,"day":3,"isLeapMonth":false,"year":2025,"era":1},{"year":2025,"month":3,"era":1,"day":4,"isLeapMonth":false,"calendar":{"identifier":"gregorian","current":1,"firstWeekday":1,"minimumDaysInFirstWeek":1,"timeZone":{"identifier":"Asia\/Tokyo"},"locale":{"current":1,"identifier":"en_JP"}}}]
 
 Any help is greatly appreciated.
1
0
28
2d
Data Transfer or Upload to Cloudkit in Published Mode
So i created an App and for some time it was working fine. The app has features to show pdf to users without logging in. I needed to upload all data to cloudkit on public database. I was not having knowledge that there are 2 mode being a noob in coding so after i saved all records in development mode in cloudkit when i published my app, i was not able to see them (Reason because live mode works in Production mode). So i need help now to transfer data from development mode to production mode or any app or code that can help me upload all data in production mode.
1
0
24
3d
iCloud Mail being rejected by Barracuda Email Protection due to missing PTR record.
My client is using iCloud Mail with his custom domain and he communicated with many govt organizations which seem to all be using Barracuda Email Protection for their spam prevention. I have properly configured his SPF, DKIM & DMARC DNS records however his emails were still being rejected. (Email header below) I contacted Barracuda support with the email header and they replied saying that the emails were rejected becuase Apple Mail has missing PTR records. I have sent dozens of emails for testing and looking at all their headers I can see (ms-asmtp-me-k8s.p00.prod.me.com [17.57.154.37]) which does not have a PTR record. ----FULL EMAIL HEADER WITH 3RD PARTY DOMAINS REMOVED----- <recipient_email_address>: host d329469a.ess.barracudanetworks.com[209.222.82.255] said: 550 permanent failure for one or more recipients (recipient_email_address:blocked) (in reply to end of DATA command) Reporting-MTA: dns; p00-icloudmta-asmtp-us-west-3a-100-percent-10.p00-icloudmta-asmtp-vip.icloud-mail-production.svc.kube.us-west-3a.k8s.cloud.apple.com X-Postfix-Queue-ID: 8979C18013F8 X-Postfix-Sender: rfc822; sender_email_address Arrival-Date: Thu, 20 Mar 2025 12:30:05 +0000 (UTC) Final-Recipient: rfc822; @****** Original-Recipient: rfc822;recipient_email_address Action: failed Status: 5.0.0 Remote-MTA: dns; d329469a.ess.barracudanetworks.com Diagnostic-Code: smtp; 550 permanent failure for one or more recipients (recipient_email_address:blocked) Return-Path: <sender_email_address> DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=sender_domain; s=sig1; bh=CyUt/U7mIHwXB5OQctPjRH/OxLH7GsLR54JjGuRkj9Y=; h=From:Message-Id:Content-Type:Mime-Version:Subject:Date:To:x-icloud-hme; b=hwEbggsctiCRlMlEgovBTjB/0sPRCb2k+1wzHRZ2dZNrZdOqvFSNWU+Aki9Bl8nfv eEOoXz5qWxO2b2rEBl08lmRQ3hCyroayIn4keBRrgkxL1uu4zMTaDUHyau2vVnzC3h ZmwQtQxiu7QvTS/Sp8jjJ/niOPSzlfhphqMxnQAZi/jmJGcZPadT8K+7+PhRllVnI+ TElJarN1ORQu+CaPGhEs9/F7AIcjJNemnVg1cude7EUuO9va8ou49oFExWTLt7YSMl s+88hxxGu3GugD3eBnitzVo7s7/O9qkIbDUjk3w04/p/VOJ+35Mvi+v/zB9brpYwC1 B4dZP+AhwJDYA== Received: from smtpclient.apple (ms-asmtp-me-k8s.p00.prod.me.com [17.57.154.37]) by p00-icloudmta-asmtp-us-west-3a-100-percent-10.p00-icloudmta-asmtp-vip.icloud-mail-production.svc.kube.us-west-3a.k8s.cloud.apple.com (Postfix) with ESMTPSA id 8979C18013F8; Thu, 20 Mar 2025 12:30:05 +0000 (UTC) From: Marcel Brunel <sender_email_address> Message-Id: <2E8D69EA-FCA6-4F5D-9D42-22A955C073F6@sender_domain> Content-Type: multipart/alternative; boundary="Apple-Mail=_F9AC7D29-8520-4B25-9362-950CB20ADEC5" Mime-Version: 1.0 (Mac OS X Mail 16.0 (3826.400.131.1.6)) Subject: Re: [EXTERNAL] - Re: Brunel - 2024 taxes Date: Thu, 20 Mar 2025 07:29:27 -0500 In-Reply-To: <SA0PR18MB350300DE7274C018F66EEA24F2D82@SA0PR18MB3503_namprd18_prod_outlook_com> To: Troy Womack <recipient_email_address> References: <SA0PR18MB350314D0B88E283C5C8E1BB6F2DE2@SA0PR18MB3503_namprd18_prod_outlook_com> <9B337A3E-D373-48C5-816F-C1884BDA6F42@sender_domain> <SA0PR18MB350341A7172E8632D018A910F2D82@SA0PR18MB3503_namprd18_prod_outlook_com> <SA0PR18MB350300DE7274C018F66EEA24F2D82@SA0PR18MB3503_namprd18_prod_outlook_com> X-Mailer: Apple Mail (2.3826.400.131.1.6) X-Proofpoint-ORIG-GUID: uqebp2OIbPqBr3dYsAxdFVkCNbM5Cxyl X-Proofpoint-GUID: uqebp2OIbPqBr3dYsAxdFVkCNbM5Cxyl X-Proofpoint-Virus-Version: vendor=baseguard engine=ICAP:2.0.293,Aquarius:18.0.1093,Hydra:6.0.680,FMLib:17.12.68.34 definitions=2025-03-20_03,2025-03-19_01,2024-11-22_01 X-Proofpoint-Spam-Details: rule=notspam policy=default score=0 bulkscore=0 clxscore=1030 suspectscore=0 mlxlogscore=999 mlxscore=0 phishscore=0 malwarescore=0 spamscore=0 adultscore=0 classifier=spam adjust=0 reason=mlx scancount=1 engine=8.19.0-2411120000 definitions=main-2503200077
0
0
37
3d
CloudKit Server-to-Server Authentication Fails with 401 Error
I'm trying to set up server-to-server authentication with CloudKit Web Services, but keep getting AUTHENTICATION_FAILED errors. I've tried multiple environment settings and debugging approaches without success. What I've Tried I created a Swift script to test the connection. Here's the key part that handles the authentication: // Get current ISO 8601 date let iso8601Formatter = ISO8601DateFormatter() iso8601Formatter.formatOptions = [.withInternetDateTime] let dateString = iso8601Formatter.string(from: Date()) // Create SHA-256 hash of request body let bodyHash = SHA256.hash(data: bodyData).compactMap { String(format: "%02x", $0) }.joined() // Get path from URL let path = request.url?.path ?? "/" // String to sign let method = request.httpMethod ?? "POST" let stringToSign = "\(method):\(path):\(dateString):\(bodyHash)" // Sign the string with EC private key let signature = try createSignature(stringToSign: stringToSign) // Add headers request.setValue(dateString, forHTTPHeaderField: "X-Apple-CloudKit-Request-ISO8601Date") request.setValue(KEY_ID, forHTTPHeaderField: "X-Apple-CloudKit-Request-KeyID") request.setValue(signature, forHTTPHeaderField: "X-Apple-CloudKit-Request-SignatureV1") } I've made a request to this endpoint: What's Happening I get a 401 status with this response: "uuid" : "173179e2-c5a5-4393-ab4f-3cec194edd1c", "serverErrorCode" : "AUTHENTICATION_FAILED", "reason" : "Authentication failed" } What I've Verified The key validates correctly and generates signatures The date/time is synchronized with the server The key ID matches what's in CloudKit Dashboard I've tried all three environments: development, Development (capital D), and production The container ID is formatted correctly Debug Information My debugging reveals: The EC key is properly formatted (SEC1 format) Signature generation works No time synchronization issues between client and server All environment tests return the same 401 error Questions Has anyone encountered similar issues with CloudKit server-to-server authentication? Are there specific container permissions needed for server-to-server keys? Could there be an issue with how the private key is formatted or processed? Are there any known issues with the CloudKit Web Services API that might cause this? Any help would be greatly appreciated!
1
0
33
3d
Critical: Cannot Deploy CloudKit Schema to Production Environment - Internal Error
Hi Developer Community, I'm experiencing a critical issue with CloudKit schema deployment that's blocking my app release. I've been trying to resolve this for several days and would appreciate any assistance from the community or Apple engineers. Issue Description I'm unable to deploy my CloudKit schema from development to production environment. When attempting to deploy through the CloudKit Dashboard, I either get an "Internal Error" message or the deployment button is disabled. Environment Details App: Reef Trak (Reef aquarium tracking app) CloudKit Container: ************ Development Environment: Schema fully defined and working correctly Production Environment: No schema deployed (confirmed in dashboard) What I've Tried Using the "Deploy Schema to Production" button in CloudKit Dashboard (results in "Internal Error") Exporting schema from development and importing to production (fails) Using CloudKit CLI tools with API token (results in "invalid-scope" errors) Waiting 24-48 hours between attempts in case of propagation delays Current Status App works perfectly in development environment (when run from Xcode) In TestFlight/sideloaded builds (production environment), the app attempts to fetch records but fails with "Did not find record type: Tank" errors Log snippet showing the issue: [2025-03-21] [CloudKit] Schema creation failed: Error saving record <CKRecordID: 0x******; recordName=SchemaSetup_Tank_-**---****, zoneID=_defaultZone:defaultOwner> to server: Cannot create new type Tank in production schema [2025-03-21] [CloudKit] Failed to create schema for Tank after 3 attempts [2025-03-21] [CloudKit] Error creating schema for Tank: Error saving record <CKRecordID: 0x****; recordName=SchemaSetup_Tank_---**-**********, zoneID=_defaultZone:defaultOwner> to server: Cannot create new type Tank in production schema App Architecture & Critical Impact My app "Reef Trak" is built around a core data model where the "Tank" entity serves as the foundational element of the entire application architecture. The Tank entity is not just another data type - it's the primary container that establishes the hierarchical relationship for all other entities: All parameter measurements (pH, temperature, salinity, etc.) are associated with specific tanks All maintenance tasks and schedules are tank-specific All livestock (fish, corals, invertebrates) exist within the context of a tank All user achievements and progress tracking depend on tank-related activities Without the Tank schema being properly deployed to production, users experience what appears to be a completely empty application, despite successful authentication and CloudKit connection. The app shows "Successfully retrieved iCloud data" but displays no content because: The Tank record type doesn't exist in production Without Tanks, all child entities (even if their schemas existed) have no parent to associate with This creates a cascading failure where no data can be displayed or saved This issue effectively renders the entire application non-functional in production, despite working flawlessly in development. Users are left with an empty shell of an app that cannot fulfill its core purpose of reef tank management and monitoring. The inability to deploy the Tank schema to production is therefore not just a minor inconvenience but a complete blocker for the app's release and functionality. Questions Is there an alternative method to deploy schema to production that I'm missing? Could there be an issue with my account permissions or container configuration? Are there known issues with the CloudKit Dashboard deployment functionality? What's the recommended approach when the dashboard deployment fails? I've also submitted a Technical Support Incident, but I'm hoping to get this resolved quickly as it's blocking my App Store release. Thank you for any assistance!
3
0
77
4d
Multible saved accounts and SwiftData
For a CRM application, I want users to be able to switch between accounts and have their saved contacts stored locally. Whenever a user logs in, the app should fetch data from their specific database location. What’s the best practice to achieve this? Should I create a separate database for each user? Should I store all the data in one database and filter it by user? Or is there a better approach I should consider?
1
0
74
1w
UserDefaults to SwifData Migration
Is there a way to move user data from UserDefaults to SwiftData when the app is in production so that people don’t lose their data. Currently my audio journals in my journal app has everything in the UserDefaults. Now this is bad for obvious reasons but I was thinking if there was a way. It’s only been 1 week since published and I have already had17 people download it.
1
0
85
1w
iCloud -> Containers display name
Hey guys, I'm developing a Swift app, using iCloud to store some data in Containers, and the new Containers I created are iCloud.com.***.dev . Therefore, there is a storage called dev in Settings -> icloud -> Manage Account Storage. Currently, the app is still under development and has not been released to the Appstore. My question: Settings -> icloud -> Manage Account Storage does not display my app name and icon, but only the suffix of the Containers id. Will this change after it is released to the Appstore? Are there any other control methods? Thank you
1
0
149
1w
Using any SwiftData Query causes app to hang
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?
1
0
134
1w
How to provide visual feedback about iCloud sync status when the user reinstalls an app?
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.
2
0
154
1w
Debugging/Fixing deleted relationship objects with SwiftData
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!
2
0
243
1w
Sync an interactive widget's Core Data store with the main app (and iCloud)
Hi everyone! I have an app on the App Store that uses Core Data as its data store. (It's called Count on Me: Tally Counter. Feel free to check it out.) One of the app's core feature is an interactive widget with a simple button. When the button is tapped, it's supposed to update the entity in the store. My requirement is that the changes are then reflected with minimal latency in the main app and – ideally – also on other devices of the same iCloud user. And vice-versa: When an entity is updated in the app (or on another device where the same iCloud user is logged in), the widget that shows this entity should also refresh to reflect the changes. I have read multiple articles, downloaded sample projects, searched Stackoverflow and the Apple developer forums, and tried to squeeze a solution out of AI, but couldn't figure out how to make this work reliably. So I tried to reduce the core problem to a minimal example project. It has two issues that I cannot resolve: When I update an entity in the app, the widget is immediately updated as intended (due to a call to WidgetCenter's reloadAllTimelines method). However, when I update the same entity from the interactive widget using the same app intent, the changes are not reflected in the main app. For the widget and the app to use the same local data store, I need to enable App Groups in both targets and set a custom location for the store within the shared app group. So I specify a custom URL for the NSPersistentStoreDescription when setting up the Core Data stack. The moment I do this, iCloud sync breaks. Issue no. 1 is far more important to me as I haven't officially enabled iCloud sync yet in my real app that's already on the App Store. But it would be wonderful to resolve issue no. 2 as well. Surely, there must be a way to synchronize changes to the source of truth triggered by interactive widget with other devices of the same iCloud user. Otherwise, the feature to talk to the main app and the feature to synchronize with iCloud would be mutually exclusive. Some other developers I talked to have suggested that the widget should only communicate proposed changes to the main app and once the main app is opened, it processes these changes and writes them to the NSPersistentCloudKitContainer which then synchronizes across devices. This is not an option for me as it would result in a stale state and potential data conflicts with different devices. For example, when a user has the same widget on their iPhone and their iPad, taps a button on the iPhone widget, that change would not be reflected on the iPad widget until the user decides to open the app on the iPhone. At the same time, the user could tap the button multiple times on their iPad widget, resulting in a conflicting state on both devices. Thus, this approach is not a viable solution. An answer to this question will be greatly appreciated. The whole code including the setup of the Core Data stack is included in the repository reference above. Thank you!
2
0
193
1w
custom share workflow
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 ?
2
0
224
1w
CloudKit keyvalue pair debug ?
Hello ! I am using this iCloud key value pair mechanism to save small app configuration between iOS and tvOS. I would say it is working. But when I go back and forth between debug and release (TestFlight) modes, it is like both apps are not connected anymore. I spend a lot of time restarting all devices, rebuilding, activating / deactivating iCloud capabilities in the Xcode project. It is like the app is mixing debug and release data. Is there an easy way to check what is happening exactly ? I know there's nothing on CloudKit console, so .... Thank you Frederic
3
0
212
1w
Can personal information be taken from creatorUserRecordID in a CKrecord?
I am using cloudkit to save users high scores in a public database. The preference over using Game Center is because of simplicity and works really well for what I want to achieve. I simply want to let users know their global position. Because of data privacy laws the app asks the user for their permission to submit their score each time they get a new high score. However, I have noticed that CKRecords under 'created' and 'modified' in addition to UTC time and date also contain creatorUserRecordID. Could this be a privacy issue? Can you extract any personal information from this? Can this be used to track back to the user? Is it linked to CKUserIdentity which I understand does contain personal information, although as I understand you need users consent to get this information. Under creatorUserRecordID it says... "Every user of the app has a unique user record that is empty by default. Apps can add data to the user record on behalf of the user, but don’t store sensitive data in it" Currently I simply ask the user if they are happy to submit their score. But do I need to point out that it also stores a creatorUserRecordID? Obviously I don't want to do this if it is not needed as the user will 1) Probably not understand what a creatorUserRecordID is and 2) It makes the question complicated and will likely make most people refuse to submit their score. If it is a privacy issue, is there anyway to stop a CKRecord creating this ID and simply save a score? All I need is a list of scores so the app can determine their current position. If creatorUserRecordID does not contain any personal details and cannot be tracked back to the user please let me know, so I can be reassured that my current set up is fine and I am not causing any privacy issues! This post did seem to indicate you may possibly be able to fetch personal details?? https://stackoverflow.com/questions/55782166/how-do-i-fetch-any-info-about-user-that-modified-ckrecord
3
0
261
1w
How to diagnose spurious SwiftDataMacros error
I have a Package.swift file that builds and runs from Xcode 15.2 without issue but fails to compile when built from the command line ("swift build"). The swift version is 6.0.3. I'm at wits end trying to diagnose this and would welcome any thoughts. The error in question is error: external macro implementation type 'SwiftDataMacros.PersistentModelMacro' could not be found for macro 'Model()'; plugin for module 'SwiftDataMacros' not found The code associated with the module is very vanilla. import Foundation import SwiftData @Model public final class MyObject { @Attribute(.unique) public var id:Int64 public var vertexID:Int64 public var updatedAt:Date public var codeUSRA:Int32 init(id:Int64, vertexID:Int64, updatedAt:Date, codeUSRA:Int32) { self.id = id self.vertexID = vertexID self.updatedAt = updatedAt self.codeUSRA = codeUSRA } public static func create(id:Int64, vertexID:Int64, updatedAt:Date, codeUSRA:Int32) -> MyObject { MyObject(id: id, vertexID: vertexID, updatedAt: updatedAt, codeUSRA: codeUSRA) } } Thank you.
0
1
229
2w
SwiftData duplicates values inside array on insert()
After copying and inserting instances I am getting strange duplicate values in arrays before saving. My models: @Model class Car: Identifiable { @Attribute(.unique) var name: String var carData: CarData func copy() -> Car { Car( name: "temporaryNewName", carData: carData ) } } @Model class CarData: Identifiable { var id: UUID = UUID() var featuresA: [Feature] var featuresB: [Feature] func copy() -> CarData { CarData( id: UUID(), featuresA: featuresA, featuresB: featuresB ) } } @Model class Feature: Identifiable { @Attribute(.unique) var id: Int @Attribute(.unique) var name: String @Relationship( deleteRule:.cascade, inverse: \CarData.featuresA ) private(set) var carDatasA: [CarData]? @Relationship( deleteRule:.cascade, inverse: \CarData.featuresB ) private(set) var carDatasB: [CarData]? } The Car instances are created and saved to SwiftData, after that in code: var fetchDescriptor = FetchDescriptor<Car>( predicate: #Predicate<Car> { car in car.name == name } ) let cars = try! modelContext.fetch( fetchDescriptor ) let car = cars.first! print("car featuresA:", car.featuresA.map{$0.name}) //prints ["green"] - expected let newCar = car.copy() newCar.name = "Another car" newcar.carData = car.carData.copy() print("newCar featuresA:", newCar.featuresA.map{$0.name}) //prints ["green"] - expected modelContext.insert(newCar) print("newCar featuresA:", newCar.featuresA.map{$0.name}) //prints ["green", "green"] - UNEXPECTED! /*some code planned here modifying newCar.featuresA, but they are wrong here causing issues, for example finding first expected green value and removing it will still keep the unexpected duplicate (unless iterating over all arrays to delete all unexpected duplicates - not optimal and sloooooow).*/ try! modelContext.save() print("newCar featuresA:", newCar.featuresA.map{$0.name}) //prints ["green"] - self-auto-healed??? Tested on iOS 18.2 simulator and iOS 18.3.1 device. Minimum deployment target: iOS 17.4 The business logic is that new instances need to be created by copying and modifying previously created ones, but I would like to avoid saving before all instances are created, because saving after creating each instance separately takes too much time overall. (In real life scenario there are more than 10K objects with much more properties, updating just ~10 instances with saving takes around 1 minute on iPhone 16 Pro.) Is this a bug, or how can I modify the code (without workarounds like deleting duplicate values) to not get duplicate values between insert() and save()?
8
0
269
2w
Friend Connection ( User A / User B) Problem
I implemented the cloudkit function, where users can connect with each other. The problem is, that if User A is doing a friend request and User B is accepting the request. The friend entry is correct visible for User B but not for User A. I can see in cloud kit that after the accepted request, the friend connection is set up correctly, also with the correct userID, but it not showing up for User A (the one that send the request)
3
0
307
2w