I am trying to read and write a text file from an App written in Swift in XCode directly to the "iCloud Drive" folder in Files on the iPhone.
The app worked readlly reading and writing to the Documents folder in the App container, and then readily to the "On My iPhone" folder in Files after adding 2 lines to the plist that I found in a search online.
But I have been unable to get to the iCloud Drive folder.
I found an item called "Enabling Document Storage in iCloud Drive" in "iCloud Design Guide" with additional plist entries that states "These settings allow iCloud Drive to provide public access to the files stored in your app’s container":
NSUbiquitousContainers
iCloud.com.example.MyApp
NSUbiquitousContainerIsDocumentScopePublic
NSUbiquitousContainerSupportedFolderLevels
Any
NSUbiquitousContainerName
MyApp
I think I changed the MyApp items appropriately.
I have enabled iCloud in my App and the XCode General, and Signing entries.
But this does not work. There are no error messages and no "Steps" shown in the "Capabilities" entry in Xcode.
A little help? :-)
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
57 Posts
Sort by:
Post
Replies
Boosts
Views
Activity
In Apple Numbers and similar apps, a user can save a document to iCloud Drive, and collaborate with other users. From what I can gather, it seems to use two mechanisms: the document as a whole is synced via iCloud Drive, but when a collaboration is started, it seems to use CloudKit records to do live updates.
I am working on a similar app, that saves documents to iCloud Drive (on Mac, iPad, and iPhone). Currently it only syncs via iCloud Drive, re-reading the entire (often large) document when a remote change occurs. This can lead to a delay of several seconds (up to a minute) for the document to be saved, synced to the server, synced from the server, and re-read.
I'm working on adding a "live sync", i.e. the ability to see changes in as near to real-time as feasible, like in Apple's apps.
The document as a whole will remain syncing via iCloud Drive. My thought is to add a CloudKit CKRecord-based sync when two or more users are collaborating on a document, recording only the diffs for quick updates. The app would no longer re-read the entire document when iCloud Drive updates it while in use, and would instead read the CloudKit records and apply those changes. This should be much faster.
Is my understanding of how Apple does it correct? Does my proposed approach seem sensible? Has anyone else implemented something like this, with iCloud Drive-based documents and a CloudKit live sync?
In terms of technologies, I see that Apple now has a Shared with You framework, with the ability to use a NSItemProvider to start the collaboration. Which raises the question, should I use the iCloud Drive document for the collaboration (as I do now), or the CloudKit CKShare diff? I think I'd have to use the document as a whole, both so it works with the Send Copy option, and so a user that doesn't have the document gets it when using Collaborate. Once the collaboration is underway, I'd want to start the CloudKit channel. So I guess I'd save the CKShare to the server, get its URL, and save that in the document, so another user can read that URL as part of their initial load of the document from iCloud Drive?
Once two (or more) users have the document via iCloud Drive, and the CKShare via the embedded URL, I should be able to do further live-sync updates via CloudKit. If a user closes the document and re-opens it, they'd get the updates via iCloud Drive, so no need to apply any updates from before the document was opened.
Does all this sound reasonable, or am I overlooking some gotcha? I'd appreciate any advice from people who have experience with this kind of syncing.
I am unable to download file from iCloud Documents from my swift project. I was able to successfully upload the file to iCloud Documents but now when I try to download same file at the uploaded path. It is giving me error that I don't have permission to view the file.
Please find exact error below.
[ERROR] couldn't fetch remote operation IDs: NSError: Cocoa 257 "The file couldn’t be opened because you don’t have permission to view it."
"Error returned from daemon: Error Domain=com.apple.accounts Code=7 "(null)""
My app uses UIDocumentPickerViewController to display image files that are saved on iCloud Drive.
In previous versions of iOS the user could long press on an image file and an option to Delete was shown. This no longer seems to be the case in iOS 18.
Is there a way to allow users to delete files when using a UIDocumentPickerViewController?
I got 16 pro max and did restore from iCloud.
all system files are downloaded but apps are getting stack at roughly 60%
tried to delete the app and download via AppStore
hard reset
changing language
go on different wifi and use mobile data as well
Any idea how to fix?
Since iOS 18, I have gotten user reports that the UIDocumentPickerViewController directoryURL is no longer opening the correct folder. Instead it is just loading the root directory of the Files app/iCloud files.
Did something change in iOS 18 that I need to account for? Not all users are having this issue, but some are and they are frustrated because a major feature of my app was to allow users to save files at the ubiquityURL.
I use the following to get the path:
NSURL *rootDirectory = [[[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil] URLByAppendingPathComponent:[NSString stringWithFormat:@"Documents/Photos/%@", folderName]];
Is there something that I need to do differently now in iOS 18 to prevent this from happening?
I'm using SwiftData, and I'm using iCloud's CloudKit feature to back up my data.
The problem here is that once you start backing up your data, you can't erase it completely.
Even if the user adds 4 data and erases 4 again, I'm using about 2.5kb.
I don't know how the user using the app will accept this.
I'm trying to provide the user with the ability to erase data at once, what should I do??
Hi,
With UIDocumentPickerViewController, there is a directoryURL property that says we can use to 'specify the starting directory for the document picker'. But it's not clear how to get the directory of a folder in iCloud Drive / Files app. How can I get the 'root' directory for a user's iCloud Drive or Dropbox folder, or the Downloads folder on their device, that I could pass to this directoryURL to make it easier for the user to pick their files?
Thanks.
Hi,
I'm working on integrating iCloud Drive functionality into my app. I noticed that the folder for my app appears under /Users/USERNAME/Library/Mobile Documents/MY_CONTAINER, but it doesn't show up in iCloud Drive.
Am I missing a step in the setup or configuration? Any guidance would be appreciated!
Thanks!
struct ModelContainerSetup {
static let shared = ModelContainerSetup()
private static let containerIdentifier = "iCloud.Journal"
func setupModelContainer() -> ModelContainer {
let schema = Schema([User.self])
let modelConfiguration = ModelConfiguration(
schema: schema,
isStoredInMemoryOnly: false,
cloudKitDatabase: .private(Self.containerIdentifier)
)
do {
return try ModelContainer(for: schema, configurations: [modelConfiguration])
} catch {
fatalError("Could not create ModelContainer: \(error)")
}
}
**Expected Behavior:
**
When CloudKit storage is full, the app should continue functioning with local storage
Data should persist locally even if cloud sync fails
Sync should resume when storage becomes available
**Actual Behavior:
**
ModelContainer initialization fails completely
Local data also stops getting saved
**Environment:
**
iOS 17.0+
SwiftData
Private CloudKit database
Ideal Behaviour:
When iCloud fails, the data should still be saved locally. I do not want to have two different containers so that I can maintain data consistency.
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.
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.