iCloud & Data

RSS for tag

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

CloudKit Documentation

Post

Replies

Boosts

Views

Activity

Inquiry Regarding Data Migration Using Quick Start
I am currently developing an iOS app with a new feature that utilizes Quick Start for data migration between devices. We are testing this in a test environment using an app distributed via TestFlight. However, we are encountering an issue where the app installed on the pre-migration device (distributed via TestFlight) does not transfer to the post-migration device. Could this issue be related to the fact that the app was distributed via TestFlight? Is there any restriction where only apps released via the App Store can be migrated using Quick Start? We would appreciate it if you could provide some insights into the cause of this issue and any alternative testing methods.
1
0
220
Oct ’24
SwiftData crash on fetch
I have a strange crash which I have problems understanding. It only happens on a few devices, after a ModelContainer migration, and it doesn't seem to crash on the migration itself. The fetch is done in onAppear, and shouldn't necessarily result in a crash, as it is an optional try: let request = FetchDescriptor<Rifle>() let data = try? modelContext.fetch(request) if let data, !data.isEmpty { rifle = data.first(where: { $0.uuid.uuidString == settings.selectedRifleId }) ?? data.first! } When I get logs from users, there seems to be an error in encoding? Exception Type: EXC_BREAKPOINT (SIGTRAP) Exception Codes: 0x0000000000000001, 0x000000018e8bfd78 Termination Reason: SIGNAL 5 Trace/BPT trap: 5 Terminating Process: exc handler [71687] Triggered by Thread: 0 Thread 0 name: Dispatch queue: com.apple.main-thread Thread 0 Crashed: 0 libswiftCore.dylib 0x18e8bfd78 _assertionFailure(_:_:file:line:flags:) + 264 1 SwiftData 0x24e18b480 0x24e14c000 + 259200 2 SwiftData 0x24e193968 0x24e14c000 + 293224 3 SwiftData 0x24e195a78 0x24e14c000 + 301688 4 libswiftCore.dylib 0x18e8e4084 _KeyedEncodingContainerBox.encodeNil<A>(forKey:) + 352 5 libswiftCore.dylib 0x18e8d79f0 KeyedEncodingContainer.encodeNil(forKey:) + 64 6 SwiftData 0x24e19f09c 0x24e14c000 + 340124 7 SwiftData 0x24e1a3dec 0x24e14c000 + 359916 8 libswiftCore.dylib 0x18ec10be8 dispatch thunk of Encodable.encode(to:) + 32 9 SwiftData 0x24e1cd500 0x24e14c000 + 529664 10 SwiftData 0x24e1cd0c8 0x24e14c000 + 528584 11 SwiftData 0x24e1da960 0x24e14c000 + 584032 12 SwiftData 0x24e1ee2ec 0x24e14c000 + 664300 13 SwiftData 0x24e1d97d8 0x24e14c000 + 579544 14 SwiftData 0x24e1eada0 0x24e14c000 + 650656 15 SwiftData 0x24e1d989c 0x24e14c000 + 579740 16 SwiftData 0x24e1eee78 0x24e14c000 + 667256 17 Impact 0x1027403bc 0x10268c000 + 738236
2
2
214
Oct ’24
My Swift concurrency is no longer running properly and it's screwing up my SwiftData objects
I have a bug I've come across since I've upgraded Xcode (16.0) and macOS (15.0 Sequoia) and figured I'd create a minimal viable example in case someone else came across this and help. I've noticed this in both the macOS and iOS version of my app when I run it. Essentially I have an area of my code that calls a class that has a step 1 and 2 process. The first step uses async let _ = await methodCall(...) to create some SwiftData items while the second step uses a TaskGroup to go through the created elements, checks if an image is needed, and syncs it. Before this worked great as the first part finished and saved before the second part happened. Now it doesn't see the save and thus doesn't see the insertions/edits/etc in the first part so the second part just isn't done properly. Those step one changes are set and shown in the UI so, in this case, if I run it again the second part works just fine on those previous items while any newly created items are skipped. I came across this issue when step one handled 74 inserts as each one didn't contain an image attached to it. When I switched the async let _ = await methodCall(...) to a TaskGroup, hoping that would wait better and work properly, I had the same issue but now only 10 to 30 items were created from the first step. Minimal Viable Example: to reproduce something similar In my minimal viable sample I simplified it way down so you can't run it twice and it's limited it creating 15 subitems. That said, I've hooked it up with both an async let _ = await methodCall(...) dubbed AL and a TaskGroup dubbed TG. With both types my second process (incrementing the number associated with the subissue/subitem) isn't run as it doesn't see the subitem as having been created and, when run with TaskGroup, only 12 to 15 items are created rather that the always 15 of async let. Code shared here: https://gist.github.com/SimplyKyra/aeee2d43689d907d7a66805ce4bbf072 And this gives a macOS view of showing each time the button is pressed the sub issues created never increment to 1 while, when using TaskGroup, 15 isn't guaranteed to be created and remembered. I'm essentially wondering if anyone else has this issue and if so have you figured out how to solve it? Thanks
2
0
292
Sep ’24
how can I discern which SwiftData object trigger the .NSManagedObjectContextDidSave notification ?
Presently, I am encountering an issue with SwiftData. For instance, I have a SwiftData class Ledger that encompasses an array of SingleTransaction, which is also a SwiftData class. Here is the question: when I save a Ledger, how can I discern that the .NSManagedObjectContextDidSave notification was triggered by saving the Ledger and not by saving a SingleTransaction? This distinction is crucial to circumvent unnecessary updates. I attempted the following syntax, but Xcode indicates that Cast from NSManagedObject to unrelated type Ledger always fails. List {...} .onReceive( NotificationCenter .default .publisher(for: .NSManagedObjectContextDidSave) .receive(on: DispatchQueue.main), perform: { notification in if let userInfo = notification.userInfo, let updatedObjects = userInfo[NSUpdatedObjectsKey] as? Set<NSManagedObject> { if updatedObjects.contains(where: { $0 is Ledger }) { fetchLedgers() } } } ) What can I do?
3
0
331
Oct ’24
How can my app access any cloud drive app?
My app needs to share data files with multiple devices owned by a single user. I also want to implement this mechanism without setting up a server. Therefore, I want to make it read/write to local data on the user's own cloud drive (e.g. iCloud, Google Drive, One Drive, Dropbox) and read/use them as needed. I have tried “.fileImporter” to get the URL, but the button is grayed out and cannot be opened. Sorry for my poor English. struct FilePathSettingView: View { @State private var isPickerPresented: Bool = false var fileControll = FileControll() var body: some View { VStack { Text("Storage Setting") Button(action:{ isPickerPresented = true }) { Text("Select place") } .fileImporter( isPresented: $isPickerPresented, allowedContentTypes: [.directory, .folder], allowsMultipleSelection: false, onCompletion: { result in switch result { case .success(let urls): guard let url = urls.first else { return } let accessGranted = url.startAccessingSecurityScopedResource() defer { if accessGranted { url.stopAccessingSecurityScopedResource() } } guard accessGranted else { print("Failed to access security-scoped resource.") return } fileControll.createDirectoryStructure(in: url) case .failure(let error): print("Failed to select directory: \(error.localizedDescription)") } } ) } } }
2
0
260
Sep ’24
Downloading files from iCloud
I'm trying to safely perform the apparently complex task for a cloud storage API, namely "downloading files", but it seems like iCloud APIs are comically broken beyond repair: -[NSFileCoordinator coordinateAccessWithIntents:queue:byAccessor:] calls the accessor block before all files have finished downloading. The same API will also return success (called the block with error == nil) even if the download fails (e.g. the phone is in airplane mode). I both cases, the files requested by the intents will not exist. -[NSFileManager startDownloadingUbiquitousItemAtURL:error:] does not have a completion block (Why?!?!) Similarly, this API will return success even if it fails (e.g. airplane mode) Manually checking NSURLUbiquitousItemIsDownloadingKey is broken as well, failed downloads (e.g. Airplane mode again) will retain their "Downloading" status, and NSURLUbiquitousItemDownloadingErrorKey is never updated. How can one safely download a file from iCloud if all of the APIs are broken?
6
0
430
Sep ’24
@Relationship crash on ios17.5 but not on ios18
In my app, I worked with ios18 by default and I had no issue, everything was working fine. However, when I wanted to test it with an iOS 17.5 simulator or real device, it is unusable because it crash when object with a relationship are created. on the first line you can see my relationship, and under it it is the extended relationship macro unmodifiable. has someone already encountered this? any clue of a hide modification of relationship working behavior in ios18? this is really annoying cause it make me unable to reduce the minimum deployment target of my app to ios17
4
0
429
Sep ’24
After upgrading to XCode 16 app stopped working
Building an app, which worked fine until I updated to XCode 16. The app parses data and saves it to SwiftData, and later that store is used for filtering in data. If I create the store on iOS 18, the store created has issues with relationships, so filtering is not working (I hope that will be fixed in iOS 18.1), so I need to create the store on iOS 17.5. But before saving the parsed objects to the SwiftData (store), I do the checking for dupes. And after Xcode 16 update that is not working anymore on iOS 17.5, (but this part is working fine under iOS 18): Here is my object: import Foundation import SwiftData @Model class CaliberData: Identifiable { var id: UUID = UUID() var sizeHeights: [SizeObject] var featuresABCDIds: [Int] init( id: UUID, sizeHeights: [SizeObject], featuresABCDIds: [Int], ) { self.id = id self.sizeHeights = sizeHeights self.featuresABCDIds = featuresABCDIds } extension CaliberData: Equatable { static func == (lhs: CaliberData, rhs: CaliberData) -> Bool { lhs.featuresABCDIds == rhs.featuresABCDIds && lhs.sizeHeights == rhs.sizeHeights } } SizeObject if needed: @Model class SizeObject: Identifiable, Equatable { @Attribute(.unique) var id: Float @Relationship(inverse: \CaliberData.sizeHeights) private(set) var caliberDataSizesX: [CaliberData]? init(_ size: Float) { self.id = size } } When I am doing the caliberData1 == CaliberData2 comparison to remove dupes before inserting to the SwifData modelContext I am getting exception, and Xcode shows it inside getter part of this expanded section under sizeHeights definition: @storageRestrictions(accesses: _$backingData, initializes: _sizeHeights) init(initialValue) { _$backingData.setValue(forKey: \.sizeHeights, to: initialValue) _sizeHeights = _SwiftDataNoType() } get { _$observationRegistrar.access(self, keyPath: \.sizeHeights) return self.getValue(forKey: \.sizeHeights) } set { _$observationRegistrar.withMutation(of: self, keyPath: \.sizeHeights) { self.setValue(forKey: \.sizeHeights, to: newValue) } } } Following is the stacktrace: #1 0x00000001cc168928 in ___lldb_unnamed_symbol4385 () #2 0x00000001cc163f34 in ___lldb_unnamed_symbol4354 () #3 0x00000001cc165fc4 in ___lldb_unnamed_symbol4369 () #4 0x00000001cc169dd4 in ___lldb_unnamed_symbol4403 () #5 0x00000001cc123854 in SwiftData.PersistentModel.getValue<τ_0_0, τ_0_1 where τ_1_0: SwiftData.RelationshipCollection, τ_1_1 == τ_1_0.PersistentElement>(forKey: Swift.KeyPath<τ_0_0, τ_1_0>) -> τ_1_0 () #6 0x0000000105eda3b0 in CaliberData.sizeHeights.getter at /var/folders/5y/vv3v98ms7jj3z4kj0f3d6f9h0000gq/T/swift-generated-sources/@__swiftmacro_11CaliberDataC11sizeHeights18_PersistedPropertyfMa_.swift:9 #7 0x0000000105ef1a84 in static CaliberData.== infix(_:_:) at ... My assumption is that "it" thinks that object is already inside the modelContext, when it's actually not yet inserted there and should act like regular class (by regular, I mean - like not marked with @Model macro). How can I do objects comparison on iOS 17.5 with Xcode 16 (before they are inserted in modelContext)? Any other options?
3
0
263
Oct ’24
Swift data issue in queries in iOS 18, no pb in iOS 17
Dear community !!! I'm brand new in SwiftUI development. I created an app, I was almost at the end with fine tuning when I got weird behaviours with the iOS 18 version when using Swift Data. I think I'm part of the problem but I can not figure out how to solve it. I've searched, spent so many hours and feel a bit disappointed not succeeding. Here is my first problem : I've two models : @Model class Song: Codable { var uuid: UUID = UUID() var text: String = "" var creationDate: Date = Date.now var updatingDate: Date = Date.now var status: Int = 0 var nbRead: Int = 0 var speed: Float = 0.5 var language: String = "" enum CodingKeys: CodingKey { case uuid, text, creationDate, updatingDate, status, nbRead, speed, language } @Relationship(inverse: \Genre.songs) var genres: [Genre]? ... } and @Model class Genre { //var uuid: UUID var name: String = "" var color: String = "Red" var songs: [Song]? init( name: String, color: String) { //self.uuid = uuid self.name = name self.color = color } } I want to list all songs organised by sections : import SwiftData import SwiftUI struct SongsListView: View { private var searchingText: String @Environment(\.modelContext) private var modelContext @Query(sort: \Genre.name) private var genres: [Genre] @Query var songs : [Song] init(searchText: String) { if !searchText.isEmpty { let predicate = #Predicate<Song> { song in song.text.localizedStandardContains(searchText) } _songs = Query(filter: predicate) } searchingText = searchText } var body: some View { HStack{ List{ if !songs.isEmpty { ForEach(genres, id: \.name){ genre in Section(header: Text(genre.name)){ ForEach (songs){song in if let songGenres = song.genres { if songGenres.contains(genre){ NavigationLink { SongView(song: song) } label: { Text(song.text) } } } } } } .onDelete { indexSet in indexSet.forEach { index in let song = songs[index] modelContext.delete(song) } } Section(header: Text("Without Genre")) { ForEach (songs){song in if let songGenres = song.genres { if songGenres.isEmpty{ NavigationLink { SongView(song: song) } label: { Text(song.text) } } } } .onDelete { indexSet in indexSet.forEach { index in let song = songs[index] modelContext.delete(song) } } } } } .scrollContentBackground(.hidden) } } } On iOS 17, creating a new song adds it directly to the list in the Without Genre section. On iOS 18, it takes around 30 seconds to be added. I did a video, and I have a demo project to illustrate if necessary. Thanks a lot for any hint, advice !
1
0
232
Oct ’24
Swift Data Predicate Evaluation Crashes in Release Build When Generics Used
I'm using Swift Data for an app that requires iOS 18. All of my models conform to a protocol that guarantees they have a 'serverID' String variable. I wrote a function that would allow me to pass in a serverID String and have it fetch the model object that matched. Because I am lazy and don't like writing the same functions over and over, I used a Self reference so that all of my conforming models get this static function. Imagine my model is called "WhatsNew". Here's some code defining the protocol and the fetching function. protocol RemotelyFetchable: PersistentModel { var serverID: String { get } } extension WhatsNew: RemotelyFetchable {} extension RemotelyFetchable { static func fetchOne(withServerID identifier: String, inContext modelContext: ModelContext) -> Self? { var fetchDescriptor = FetchDescriptor<Self>() fetchDescriptor.predicate = #Predicate<Self> { $0.serverID == identifier } do { let allModels = try modelContext.fetch(fetchDescriptor) return allModels.first } catch { return nil } } } Worked great! Or so I thought... I built this and happily ran a debug build in the Simulator and on devices for months while developing the initial version but when I went to go do a release build for TestFlight, that build reliably crashed on every device with a message like this: SwiftData/DataUtilities.swift:65: Fatal error: Couldn't find \WhatsNew. on WhatsNew with fields [SwiftData.Schema.PropertyMetadata(name: "serverID", keypath: \WhatsNew., defaultValue: nil, metadata: Optional(Attribute - name: , options: [unique], valueType: Any, defaultValue: nil, hashModifier: nil)), SwiftData.Schema.PropertyMetadata(name: "title", keypath: \WhatsNew., defaultValue: nil, metadata: nil), SwiftData.Schema.PropertyMetadata(name: "bulletPoints", keypath: \WhatsNew.)>, defaultValue: nil, metadata: nil), SwiftData.Schema.PropertyMetadata(name: "dateDescription", keypath: \WhatsNew., defaultValue: nil, metadata: nil), SwiftData.Schema.PropertyMetadata(name: "readAt", keypath: \WhatsNew.)>, defaultValue: nil, metadata: nil)] It seems (cannot confirm) that something in the release build optimization process is stripping out some metadata / something about these models that makes this predicate crash. Tested on iOS 18.0 and 18.1 beta. How can I resolve this? I have two dozen types that conform to this protocol. I could manually specialize this function for every type myself but... ugh.
2
0
376
Oct ’24
How to use notification to notify shared container changes in cloudkit?
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.
3
0
387
Sep ’24
iOS app loses access to the Documents folder inside the iCloud ubiquity container
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?
0
1
168
Oct ’24
Does SwiftData currently supports data sharing among multiple users through iCloud?
Currently, I am planning to add a new feature to my app that allows multiple users to collaboratively manage a single legder. Initially, I chose SwiftData with iCloud for development, so I wanted to inquire whether SwiftData currently supports data sharing among multiple users through iCloud. If it does not, should I transition entirely to Core Data, or is it feasible to allow Core Data and SwiftData to work together?
1
0
346
Oct ’24
Swift Data issue with a recursive model class
Dear Apple Developer Forum As the title suggests, I have an issue with Swift Data when I want to modify a property of a recursive model class instance. Please consider the following sample project: import SwiftUI import SwiftData @main struct ISSUEApp: App { var sharedModelContainer: ModelContainer = { let schema = Schema([ Item.self, ]) let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: true) do { return try ModelContainer(for: schema, configurations: [modelConfiguration]) } catch { fatalError("Could not create ModelContainer: \(error)") } }() var body: some Scene { WindowGroup { ContentView() } .modelContainer(sharedModelContainer) } } @Model final class Item { var name: String? var parent: Item? init(name: String?, parent: Item?) { self.name = name self.parent = parent } } struct ContentView: View { @Environment(\.modelContext) private var context @Query private var items: [Item] @State private var itemToMove: Item? @State private var count: Int = 0 @State private var presentMoveView: Bool = false var body: some View { NavigationStack() { List(items, id: \.id) {item in Button(action: { itemToMove = item }, label: { Text("Id: \(item.name ?? "ERROR") and my parent iD is \(item.parent?.name ?? "root")") .bold(itemToMove == item) .italic(itemToMove == item) }) } .sheet(isPresented: $presentMoveView, content: { MoveView(toMove: self.itemToMove!) }) .toolbar { ToolbarItem(placement: .navigationBarTrailing) { Button(action: { let i = Item(name: "\(count)", parent: nil) context.insert(i) try? context.save() count += 1 }, label: { Text("Add an item") }) } ToolbarItem(placement: .navigationBarLeading) { Button(action: { presentMoveView.toggle() }, label: { Text("Move selected item") }) } } } } } struct MoveView: View { @Environment(\.modelContext) private var modelContext @Environment(\.dismiss) private var dismiss @Query private var items: [Item] @Bindable var toMove: Item @State private var selectedFutureParent: Item? var body: some View { NavigationStack(){ List(items, id: \.id) {item in Button(action: { selectedFutureParent = item }, label: { Text("Id: \(item.name ?? "ERROR") and my parent iD is \(item.parent?.name ?? "root")") .bold(selectedFutureParent == item) .italic(selectedFutureParent == item) }) } .toolbar(){ ToolbarItem{ Button("Move", action: { toMove.parent = selectedFutureParent dismiss() }) } } } } } #Preview { ContentView() .modelContainer(for: Item.self, inMemory: true) } Please launch the preview of this app, add items (as many as you'd like), select one and click on the "Move selected item" button. Select the new parent of the item. As you may have noticed, both selected items (moved item and new parent) are modified, whereas only one equality is used. This issue seems to be independent from the @Bindable property wrapper. I tried many things, such as using index instead of direct elements; using local let constant for the parent but the constant is still modified (very weird...) Thank you in advance for your help ! Best regards
1
0
332
Oct ’24
Thread Error with @Model Class
I have a @Model class that is comprised of a String and a custom Enum. It was working until I added raw String values for the enum cases, and afterwards this error and code displays when opening a view that uses the class: { @storageRestrictions(accesses: _$backingData, initializes: _type) init(initialValue) { _$backingData.setValue(forKey: \.type, to: initialValue) _type = _SwiftDataNoType() } get { _$observationRegistrar.access(self, keyPath: \.type) return self.getValue(forKey: \.type) } set { _$observationRegistrar.withMutation(of: self, keyPath: \.type) { self.setValue(forKey: \.type, to: newValue) } } } Thread 1: EXC_BREAKPOINT (code=1, subcode=0x1cc165d0c) I removed the String raw values but the error persists. Any guidance would be greatly appreciated. Below is replicated code: @Model class CopingSkillEntry { var stringText: String var case: CaseType init(stringText: String, case: CaseType) { self.stringText = stringText self.case = case } } enum CaseType: Codable, Hashable { case case1 case case1 case case3 }
2
0
233
Oct ’24
SQLLite 3 and iOS 18
Hi, I've got an app using SQLLite. Under iOS 17 I could insert and select rows with no issues. Under iOS 18 the same code runs without errors but the select returns no results. Various select statements with and without where clause's, and freshly created database files all behave the same way. Unless... the phone is in developer mode, then it works same as iOS 17. I'm assuming it's some security change, how do we fix it? Same issue with Swift 5 and Swift 6 for context but I don't think its related to Swift. Thanks !
5
0
244
Oct ’24
Backup and Restore a Flutter SQLite database file to iCloud
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)) } }
0
0
214
Oct ’24
Opening file from iCloud Desktop versus Mail attachment
Am developing an iOS App, which uses a ZipFoundation wrapper around Compression. In XCode, have exported a document type with extension '.MU' in the Info.plist. On iPhone, when attempting to open archive called: 'Snapshot-test.mu' can OPEN as a mobile email attachment but FAILED via Files App referring to "iCloud Drive/Desktop" Here are the respective URLS "file:///private/var/mobile/Containers/Data/Application/&lt;UniqueID&gt;/Documents/Inbox/Snapshot-test.mu" "file:///private/var/mobile/Library/Mobile%20Documents/com~apple~CloudDocs/Desktop/Snapshot-test1.mu" Two questions: Is it possible to grant access to files residing remotely in iCloud? Is "iCloud Drive/Desktop" unique, whereas other iCloud locations would be OK?
0
0
236
Oct ’24
CloudKit data is lost when reinstalling the app
We worked with SwiftData, and once CloudKit was integrated, the synchronization worked well. Even if I rerun the app, it works just as well. However, when I delete the app and reinstall it, I get a Token Expired error and CloudKit doesn't work properly. My code is organized like this public lazy var modelContext: ModelContext = { ModelContext(modelContainer) }() private lazy var modelContainer: ModelContainer = { let schema = Schema([ Entity1.self, Entity2.self, Entity3.self, ]) let modelConfiguration = ModelConfiguration( schema: schema, groupContainer: .identifier("myGroupContainer"), cloudKitDatabase: .automatic ) do { return try ModelContainer(for: schema, configurations: [modelConfiguration]) } catch { fatalError("Could not create ModelContainer: \(error)") } }() The error content is as follows error: CoreData+CloudKit: -[PFCloudKitImportRecordsWorkItem fetchOperationFinishedWithError:completion:]_block_invoke(707): <PFCloudKitImporterZoneChangedWorkItem: 0x3022c0000 - <NSCloudKitMirroringImportRequest: 0x3036e7ac0> 1A7E53D4-E95B-423F-8887-66360F6D8865> { ( "<CKRecordZoneID: 0x301bb1bf0; zoneName=com.apple.coredata.cloudkit.zone, ownerName=__defaultOwner__>" ) } - Fetch finished with error: <CKError 0x301bb5650: "Partial Failure" (2/1011); "Couldn't fetch some items when fetching changes"; uuid = 3F346302-C3EE-4F72-820C-988287C92C0A; container ID = "MyContainerID"; partial errors: { com.apple.coredata.cloudkit.zone:__defaultOwner__ = <CKError 0x301bb1830: "Change Token Expired" (21/2026); server message = "client knowledge differs from server knowledge"; op = 515034AC3ADC4348; uuid = 3F346302-C3EE-4F72-820C-988287C92C0A> }> error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _importFinishedWithResult:importer:](1390): <PFCloudKitImporter: 0x3000a1240>: Import failed with error: <CKError 0x301bb5650: "Partial Failure" (2/1011); "Couldn't fetch some items when fetching changes"; uuid = 3F346302-C3EE-4F72-820C-988287C92C0A; container ID = "MyContainerID"; partial errors: { com.apple.coredata.cloudkit.zone:__defaultOwner__ = <CKError 0x301bb1830: "Change Token Expired" (21/2026); server message = "client knowledge differs from server knowledge"; op = 515034AC3ADC4348; uuid = 3F346302-C3EE-4F72-820C-988287C92C0A> }> Forcing the ModelContainer to be reinitialized fixes the problem, it's a problem to get this error in the first place, the error doesn't even go to fatal for me, so I don't even know how to verify that it's happening. Is there something I'm doing wrong, or do you have any good ideas for solving the same problem?
4
1
629
May ’24