Bonjour, a chaque installation de swift playgrounds sur ipad, icloud empeche la sauvegarde et empeche donc d’ouvrir les app.
sur icloud drive les fichiers sont present mais a zero ko.
par contre les fichiers playgroundsbook fonctionnent.
la premiere solution que j’ai ***** etait de desactivé la sauvegarde icloud et ca a fonctionné en local.
mais comme je veux mes fichiers sur le icloud drive j’ai tenté une autre approche.
j’ai tenté de copié mes fichiers en local sur icloud drive ca ne fonctionne pas.
puis j’ai juste fait un drag/drop de fichier app vers le playgrounds.
l’app s’ouvre mais n’est pas sauvegardé dans icloud drive.
par contre les modifs sont bien enregistrées.
enfin j’ai refait la meme approche, une fois l’app ouverte dans playgrounds je l’ai partagé puis enregistré dans icloud.
cette fois ci le fichier est pris en compte et fonctionne.
iCloud Drive
RSS for tagiCloud Drive safely stores any kind of file so it can be accessed in iCloud-enabled apps on iPhone, iPad, Mac, or PC.
Posts under iCloud Drive tag
53 Posts
Sort by:
Post
Replies
Boosts
Views
Activity
I have existing macOS application(pkg distribution) and now I need to release App Store version
I need to move all files from "Documents/My App" to app container
however container migration doesn't work in some cases
I've tested TestFlight build:
migration works fine if Mac uses Local Documents folder
migration doesn't work if Mac uses iCloud Documents and Desktop folders
Is there some way to fix this?
container-migration.plist:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Move</key>
<array>
<string>${Documents}/My App</string>
</array>
</dict>
</plist>
As the title says, I logged in to iCloud on my simulator on my mac mini m2 and turned on icloud sync. My health data is in iCloud but it wont load in. When I go to documents for example I can see documents that I have loaded so I know something is working right.
I have tried clicking Feature -> Trigger iCloud sync with no luck.
I have tried logging out and logging back in, no luck.
I have tried Restarting the simulator with no luck.
The app I am building uses health data and there is no other way to get health data (heart rate, workouts, sleep) in the simulator. Please help, Thank you
Hi,
I have configured my ios app with iCloud Coredata sync.
I have already checked bundleId, containerId, and cloud login on the device.
I am getting the following error.
error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _performSetupRequest:]_block_invoke(1242): <NSCloudKitMirroringDelegate: 0x600003d085a0>: Failed to set up CloudKit integration for store: <NSSQLCore: 0x105814630> (URL: file:///Users/santoshsingh/Library/Developer/CoreSimulator/Devices/B49DDBBB-6111-4664-897C-08976854137E/data/Containers/Data/Application/55E67DB0-8CAE-416D-A873-161443FA690F/Library/Application%20Support/default.store)
<CKError 0x600000c786f0: "Partial Failure" (2/1011); "Failed to modify some record zones"; uuid = EC168AB2-FDDD-47C6-B6E1-8C6A52C11F55; container ID = "iCloud.com.AmeristarFence.PerimeterInSite"; partial errors: {
com.apple.coredata.cloudkit.zone:defaultOwner = <CKError 0x600000c71ec0: "Permission Failure" (10/2007); server message = "Invalid bundle ID for container"; op = FED32AB88A4F36CC; uuid = EC168AB2-FDDD-47C6-B6E1-8C6A52C11F55>
}>
CoreData: CloudKit: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _finishedRequest:withResult:]: Finished request: <NSCloudKitMirroringDelegateSetupRequest: 0x600002161c70> 26F773DB-4986-430A-A3FF-AC39B9390223 with result: <NSCloudKitMirroringResult: 0x600000c72130> storeIdentifier: CAC05ADB-DC9A-4CC5-9530-91FDDEEC7DD2 success: 0 madeChanges: 0 error: <CKError 0x600000c786f0: "Partial Failure" (2/1011); "Failed to modify some record zones"; uuid = EC168AB2-FDDD-47C6-B6E1-8C6A52C11F55; container ID = "iCloud.com.AmeristarFence.PerimeterInSite"; partial errors: {
com.apple.coredata.cloudkit.zone:defaultOwner = <CKError 0x600000c71ec0: "Permission Failure" (10/2007); server message = "Invalid bundle ID for container"; op = FED32AB88A4F36CC; uuid = EC168AB2-FDDD-47C6-B6E1-8C6A52C11F55>
}>
CoreData: CloudKit: CoreData+CloudKit: -[NSCloudKitMirroringDelegate checkAndExecuteNextRequest]: <NSCloudKitMirroringDelegate: 0x600003d085a0>: Checking for pending requests.
CoreData: CloudKit: CoreData+CloudKit: -[NSCloudKitMirroringDelegate checkAndExecuteNextRequest]_block_invoke(3569): <NSCloudKitMirroringDelegate: 0x600003d085a0>: No more requests to execute.
error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate recoverFromError:]: <NSCloudKitMirroringDelegate: 0x600003d085a0> - Attempting recovery from error: <CKError 0x600000c786f0: "Partial Failure" (2/1011); "Failed to modify some record zones"; uuid = EC168AB2-FDDD-47C6-B6E1-8C6A52C11F55; container ID = "iCloud.com.AmeristarFence.PerimeterInSite"; partial errors: {
com.apple.coredata.cloudkit.zone:defaultOwner = <CKError 0x600000c71ec0: "Permission Failure" (10/2007); server message = "Invalid bundle ID for container"; op = FED32AB88A4F36CC; uuid = EC168AB2-FDDD-47C6-B6E1-8C6A52C11F55>
}>
error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _recoverFromPartialError:forStore:inMonitor:]_block_invoke(2775): <NSCloudKitMirroringDelegate: 0x600003d085a0>: Found unknown error as part of a partial failure: <CKError 0x600000c71ec0: "Permission Failure" (10/2007); server message = "Invalid bundle ID for container"; op = FED32AB88A4F36CC; uuid = EC168AB2-FDDD-47C6-B6E1-8C6A52C11F55; container ID = "iCloud.com.AmeristarFence.PerimeterInSite">
error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _recoverFromPartialError:forStore:inMonitor:]: <NSCloudKitMirroringDelegate: 0x600003d085a0>: Error recovery failed because the following fatal errors were found: {
"<CKRecordZoneID: 0x600000c720a0; zoneName=com.apple.coredata.cloudkit.zone, ownerName=defaultOwner>" = "<CKError 0x600000c71ec0: "Permission Failure" (10/2007); server message = "Invalid bundle ID for container"; op = FED32AB88A4F36CC; uuid = EC168AB2-FDDD-47C6-B6E1-8C6A52C11F55; container ID = "iCloud.com.AmeristarFence.PerimeterInSite">";
}
I have an iOS app that writes files to its iCloud ubiquity container. The container is specified in Signing & Capabilities as iCloud.com.myappbusiness.myappid where "com.myappbusiness.myappid" is the bundle identifier. It works most of the time but for some users (less than 1%) it stops working at some point, most likely after any update of my app. Device reboot or app reinstallation does not help. What seems to help is turning off iCloud for the app in the iOS Settings (at which point the app saves files to the device locally) and then turning it on again.
I cannot replicate the issue and have to rely on user feedback. I have tried various fixes over the past half a year, added retries after timeout, error handlers, tracing, etc. But the error always appears to someone after another app update.
I have narrowed it down to the three lines of code below that check for the existence of the app iCloud container:
NSFileManager* fileManager = [[NSFileManager alloc] init];
NSURL* containerUrl = [[fileManager URLForUbiquityContainerIdentifier:nil]
URLByAppendingPathComponent:@"Documents"];
BOOL doesExist = [fileManager fileExistsAtPath:containerUrl.path];
doesExist returns NO when the issue happens. I.e. the app does not see its container and it looks like it does not exist. The folder should exist as this happens to long term users that have used the app before. Regarding the containerUrl, I can see it in the log that I get from the affected users and it is the correct path to the container, e.g. /private/var/mobile/Library/Mobile Documents/iCloud~com~myappbusiness~myappid/Documents
I have tried the code above as it is and also within a file coordinator handler:
[[[NSFileCoordinator alloc] initWithFilePresenter:nil] coordinateWritingItemAtURL:targetFileUrl
options:NSFileCoordinatorWritingForReplacing error:&error
byAccessor:^(NSURL * _Nonnull newURL) { ... the code here ... }];
I have run out of ideas what else to try. Is there anything obviously wrong with this approach or am I missing something in the code here? Is this a permission issue? Do I need to recreate the Documents folder if it's not accessible?
I'm managing the database with SQLite in Flutter.
I want to enable iCloud backup and restore on the Swift side when called from Flutter.
I am using the following source code, but it is not working.
What could be the cause?
Could you provide a method and countermeasure?
private func saveFileToICloud(fileName: String, localDatabasePath: String, result: @escaping FlutterResult) {
guard let containerName = Bundle.main.object(forInfoDictionaryKey: "ICLOUD_CONTAINER_NAME") as? String else {
result(FlutterError(code: "NO_ICLOUD_CONTAINER", message: "iCloud container is not available", details: nil))
return
}
guard let containerURL = FileManager.default.url(forUbiquityContainerIdentifier: containerName) else {
result(FlutterError(code: "NO_ICLOUD_CONTAINER", message: "iCloud container is not available", details: nil))
return
}
let fileURL = containerURL.appendingPathComponent(fileName)
let sourceURL = URL(fileURLWithPath: localDatabasePath)
do {
if FileManager.default.fileExists(atPath: fileURL.path) {
try FileManager.default.removeItem(at: fileURL)
}
try FileManager.default.copyItem(at: sourceURL, to: fileURL)
result("File saved successfully to iCloud: \(fileURL.path)")
} catch {
result(FlutterError(code: "WRITE_ERROR", message: "Failed to write file to iCloud", details: error.localizedDescription))
}
}
private func readFileFromICloud(fileName: String, localDatabasePath: String, result: @escaping FlutterResult) {
let containerName = ProcessInfo.processInfo.environment["ICLOUD_CONTAINER_NAME"]
guard let containerURL = FileManager.default.url(forUbiquityContainerIdentifier: containerName) else {
result(FlutterError(code: "NO_ICLOUD_CONTAINER", message: "iCloud container is not available", details: nil))
return
}
let fileURL = containerURL.appendingPathComponent(fileName)
let sourceURL = URL(fileURLWithPath: localDatabasePath)
do {
if FileManager.default.fileExists(atPath: sourceURL.path) {
try FileManager.default.removeItem(at: sourceURL)
}
try FileManager.default.copyItem(at: fileURL, to: sourceURL)
result("File restored successfully to sqlite: \(sourceURL.path)") } catch {
result(FlutterError(code: "READ_ERROR", message: "Failed to read file from iCloud", details: error.localizedDescription))
}
}
Our app is a document-based app that uses UIDocumentBrowserViewController. We are facing an issue when the user is creating a new document on iOS/iPadOS when in the “Recents” tab (as opposed to the “Browse” tab). Specifically, the document is saved to a hidden ubiquity container. As a result, the user cannot find the file in the document browser. It also does not appear in “Recents”. The expected behaviour would be a folder with our app's icon on it on the user’s iCloud Drive, which contains the files the user creates when in the “Recents” tab.
This issue started to happen when we introduced a new feature that uses iCloud Documents with its own ubiquity container. I'm not sure how UIDocumentBrowserViewController handled saving documents to a default location on iCloud Drive before we had the iCloud Documents entitlement enabled. All I know is that there were no issues.
How to recreate the issue:
Create a document-based app with UIDocumentBrowserViewController. Run the app and create a document while in the recents tab with iCloud enabled. The document will be stored to a folder on iCloud.
Now, enable iCloud Documents and specify a ubiquity container. Then, try to create documents in the Recents tab. The location in which the documents are created cannot be navigated to.
Using this Apple repository as a basis
https://github.com/apple/sample-cloudkit-zonesharing
I created and verified the shared zone and the same zone is private for the person who shared it and shared for the person who received it, so aren't they the same zones?
[same zone but different id?]
I can make the person who shared the zone (owner) access the zone as a .shared scope just like the person who was shared.
I'm studying sharing through this link. I followed the first steps by changing the bundle identifier of the project, the tests and placing my own container in the config and in the info.plist.
https://github.com/apple/sample-cloudkit-zonesharing
The app appears and in the log it appears that it has managed to access my iCloud, but when I click on share and share something, the following message appears in the console, on the simulator and on the iPhone:
"No options were found, providing default value for access type"
"No options were found, providing default values for permissions"
"connection invalidated"
And finally, when I click on the shared link, the following message appears:
"Item unavailable
The owner stopped sharing, or you don't have permission to open it."
I would like to create a private container and share a zone between two users with different iCloud accounts. All changes made by one would be notified with push notifications to the other user's db. Both could change the same information.
Exactly as it is done in this apple project.
https://developer.apple.com/documentation/cloudkit/shared_records/sharing_cloudkit_data_with_other_icloud_users
However, I have been reading this code for days and I am stuck on it, it is extremely complicated for my level.
I would really like to know if there is any simple project that uses the same idea to build this logic with swiftui.
Apple is Delaying the Review of a Critical iOS 17 Vulnerability to Avoid Official Acceptance and Bounty Payment
Hamed Hamedi, a security researcher, has revealed that Apple is prolonging the review process of a serious security vulnerability in the iCloud lock screen, which he discovered in iOS 17. According to Hamedi, he has submitted all the necessary evidence, including multiple videos and detailed explanations, to Apple's security team. However, despite the passage of time and providing precise information, Apple has been stalling the process by asking repetitive questions and requesting additional documentation, effectively delaying the report's resolution.
This security bug allows users to bypass the iCloud lock screen using VoiceOver and a few simple gestures, gaining access to various parts of the device. Despite the fact that all the steps are clearly demonstrated in the submitted videos, Apple has refrained from officially acknowledging the bug and processing the associated bounty.
Hamedi believes the upcoming release of the iPhone 16 and iOS 18 might be the main reason for these delays, as acknowledging the bug could negatively impact the reputation and security of Apple's new products, potentially eroding customer trust. He suspects that Apple is deliberately postponing the case to prevent the public disclosure of the vulnerability right before the launch of its new products.
Apple's delay in addressing such serious security issues raises important questions about the company's priorities in safeguarding user security and maintaining transparency in handling critical problems. It remains unclear what decision Apple will ultimately make regarding this case, but the delays have already sparked significant concern among security experts.
https://www.instagram.com/p/C_iZGUJK6ok/?igsh=MTlnMnQ0bGswM2cyYQ==
I noticed last night that workouts I have been recording on my main carry device running 17.6.x have not been syncing to my beta devices running iOS 18 RC, iPadOS 18 RC and watchOS 11 RC.
All devices are using the same Apple Account and I have iCloud enabled for Health data. The iPad running the RC has the syncing enabled in Profile.
Is anyone else experiencing health data not propagating to the 18.x devices? Some of data exists on all devices but not all. For good measure I left the device unlocked on the health app last night for a long period of time to let it do its thing. This morning the data still hadn't propagated.
I disabled and reenabled the synchronization on my iPad having chosen to delete all samples when disabling it. Hopefully all of my data dating back to the first Apple Watch in 2014 restores.
FWIW my data set according to iCloud settings my health dataset is just shy of 650 MB.
FB15102443 - Health / HealthKit: Workouts, activity rings, sample data, and more not syncing via iCloud to 18 RC device
'Remove Download' button in right click menu for iCloud folder in Finder on macOS does not work if total number of selected files/ folders at the time are more than 10 nos. If more than 10 non of files/ folders are selected at any time, then the 'Remove Download' button disappears from the right click context menu in macOS Finder for iCloud folders.
To click and act on the 'Remove Download' button on context menu of Finder upon right click, the total number of files and folders together must not exceed 10 nos.
Is this the behaviour expected, or am I missing something and this observed behaviour is a bug of Finder?
I am adding a feature to my app to import a GPX file using the Document Picker.
For some reason, this feature works just fine testing on my iPad but not my iPhone. All GPX files are disabled (lower opacity) on my iPhone so I can't select them. On my iPad, I can select these files with no issues. Both iPad and iPhone are on iOS v17.5.1. My iPhone is a 14 Pro Max and my iPad is an iPad Pro (10.5 inch) model.
Here is my Info.plist file as well as my Entitlements.plist
Let me know if you need any other information.
Info.plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>LSRequiresIPhoneOS</key>
<true />
<key>UIDeviceFamily</key>
<array>
<integer>1</integer>
<integer>2</integer>
</array>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>arm64</string>
</array>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>XSAppIconAssets</key>
<string>Assets.xcassets/appicon.appiconset</string>
<key>CFBundleIdentifier</key>
<string />
<key>NSLocationWhenInUseUsageDescription</key>
<string>Location is used to track your location while navigating routes and waypoints.</string>
<key>CFBundleShortVersionString</key>
<string>2.8.0</string>
<key>CFBundleDisplayName</key>
<string>Fish Fathom</string>
<key>UTImportedTypeDeclarations</key>
<array>
<dict>
<key>UTTypeIdentifier</key>
<string>com.topografix.gpx</string>
<key>UTTypeReferenceURL</key>
<string>http://www.topografix.com/GPX/1/1</string>
<key>UTTypeDescription</key>
<string>GPS Exchange Format (GPX)</string>
<key>UTTypeConformsTo</key>
<array>
<string>public.xml</string>
</array>
<key>UTTypeTagSpecification</key>
<dict>
<key>public.filename-extension</key>
<array>
<string>gpx</string>
</array>
<key>public.mime-type</key>
<string>application/gpx+xml</string>
</dict>
</dict>
</array>
<key>CFBundleDocumentTypes</key>
<array>
<dict>
<key>CFBundleTypeIconFiles</key>
<array />
<key>CFBundleTypeName</key>
<string>GPS Exchange Format (GPX)</string>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>LSHandlerRank</key>
<string>Owner</string>
<key>LSItemContentTypes</key>
<array>
<string>com.topografix.gpx</string>
</array>
</dict>
</array>
<key>LSSupportsOpeningDocumentsInPlace</key>
<true />
</dict>
</plist>
Entitlements.plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.developer.applesignin</key>
<array>
<string>Default</string>
</array>
<key>com.apple.developer.icloud-services</key>
<array>
<string>CloudDocuments</string>
</array>
</dict>
</plist>
I've implemented a file provider for macos, and it works well. Now I'm trying to add partial download support in my implementation. however, it doesn't seem to work.
As per documentation, I've implemented
protocol NSFileProviderPartialContentFetching
and its method
func fetchPartialContents(for: NSFileProviderItemIdentifier, version: NSFileProviderItemVersion, request: NSFileProviderRequest, minimalRange: NSRange, aligningTo: Int, options: NSFileProviderFetchContentsOptions, completionHandler: (URL?, NSFileProviderItem?, NSRange, NSFileProviderMaterializationFlags, (any Error)?) -> Void) -> Progress
Now, I'm testing my implementation, and I open a movie from my File Provider using VLC. I see that
fetchPartialContents get a hit. I download requested range, and return it through completionHandler. However VLC gives a read error.
here is my implementation of fetchPartialContents:
private func align(range: NSRange, to alignment: Int) -> NSRange {
let start = range.location - (range.location % alignment)
let end = range.location + range.length
let alignedEnd = ((end + alignment - 1) / alignment) * alignment
let alignedLength = alignedEnd - start
return NSRange(location: start, length: alignedLength)
}
unc fetchPartialContents(for itemIdentifier: NSFileProviderItemIdentifier, version requestedVersion: NSFileProviderItemVersion, request: NSFileProviderRequest, minimalRange requestedRange: NSRange, aligningTo alignment: Int, options: NSFileProviderFetchContentsOptions = [], completionHandler: @escaping (URL?, NSFileProviderItem?, NSRange, NSFileProviderMaterializationFlags, (any Error)?) -> Void) -> Progress {
let alignedRange = align(range: requestedRange, to: alignment)
let progress = Progress(totalUnitCount: 100)
let data = downloadData(for: alignedRange)
progress.completedUnitCount = 100;
tempFileHandle = try FileHandle(forWritingTo: tempFileURL)
tempFileHandle.seek(toFileOffset: UInt64(alignedRange.location))
tempFileHandle.write(data!)
tempFileHandle.closeFile()
let item = FileProviderItem(identifier: itemIdentifier,)
completionHandler(tempFileURL, item, alignedRange, [], nil)
} catch {
completionHandler(nil, nil, alignedRange, [], error)
}
}
I beleive I'm doing everhting correctly & as per documentation, but certainly there is something is wrong. Can someone help me about it?
cheers,
I have a large file saved in iCloud drive. I need just a portion of that file.
func ubiquitousData(file: URL, offset: UInt64, size: UInt64) async -> Data {
// downloads just the portion of the ubiquitous `file`.
}
FileManager already has an api that downloads the full file. Is there a way to download just a portion of the file?
Go to finder >Go >Home
you will find iCloud Drive (Archive) folder with all your folders just deleted
TL;DR: Does Apple keep a list of ubiquity containers that a user has deleted, and prevent apps from creating the same ubiquity containers again?
If so, where is this list, and how can I reset it?
Long version:
I'm developing an app that relies on having an ubiquity container (iCloud Drive folder). This was working fine until I decided to rename the folder.
I deleted the existing folder with the old name, changed the value of "NSUbiquitousContainerName," and expected my app's code to create the new folder with the new name, as it had done originally.
But the result has been a disaster.
Now, in the simulator, all of my code is running without errors. The app thinks the iCloud Drive folder exists and can read and write files to it, but the folder only seems to exist in the simulator and is not visible via any iCloud Drive UI.
When I run the exact same code on my iPhone, the code fails with the error 'You don’t have permission to save the file “Documents” in the folder “[whatever]”.'
I have tried changing my app's bundle identifier and everything works swimmingly: the iCloud Drive folder is created instantly and is visible everywhere.
So something is preventing things from working with the original bundle identifier and I need to figure out what it is and how to fix it. Does anybody have any ideas? Thanks in advance.
Keep being asked to upgrade to iCloud+ every time there’s a iOS update, even though I’m on a family plan. It disconnects me and my family and tries to upsell us every time again. We have to manually switch back. Very deceptive and pretty sketchyz
adding that since the iOS 18 beta upgrade, I have also been unable to get back onto my family plan for iCloud+ storage. The option to use the family plan has now completely disappeared and my only option is to buy another plus package which obviously isn’t required since I already subscribe to Apple One. Hopefully a fix for this comes out soon. It’s hijacking our phones now and won’t let us back up any materials even though I’ve paid for the extra space.
Apple, you really need to look into the way it kicks people off their family plan storage every time there’s an iOS upgrade as well because for some people, I’m sure they are clicking on your buy more space button, since it’s much more prominent than finding the back door way to rejoin the family plan. If that’s an intentional way to trick people into getting an upsell you’re going to end up with lawsuits. It’s not a very cool UX experience.
Hello,
im trying to parse a JSON Request into a Swift Data Model. The specific bug happens with the nutriscore.
It works perfectly fine if I do my request and Decode or Encode the Model directly. But when im trying to add it to the Database the field is empty.
Somehow when im iterating through each product (my model) and console log it, it works. But only if there is one product in my database. sometimes when im adding another product, it somehow deletes(?) all nutriscores and the console log prints "nil" for all products. even for the product it worked before.
This right here is the way I insert into my database which should be perfectly fine. And the printing works also perfectly fine and it always displays the correct nutriscore
func dataScanner(_ dataScanner: DataScannerViewController, didAdd addedItems: [RecognizedItem], allItems: [RecognizedItem]) {
for item in addedItems {
if case let .barcode(barcode) = item {
performAPIRequest(with: barcode.payloadStringValue!) { result in
switch result {
case .success(let product):
...
var descriptor: FetchDescriptor<Product> {
var descriptor = FetchDescriptor<Product>(
predicate: #Predicate { $0.code == product.code }
)
descriptor.fetchLimit = 1
return descriptor
}
var products: [Product] = []
products = try! self.parent.context.fetch(descriptor)
print(product.nutriscore ?? "no nutri"); //WORKS PERFECTLY FINE!!
if let existingProduct = products.first {
existingProduct.amount! += 1
existingProduct.lastScannedAt = Date()
} else {
self.parent.context.insert(product)
}
self.processMeals()
case .failure(let error):
print("Error: \(error)")
}
}
}
}
}
This has to be a SwiftData Bug, or why doesn't it work