[SOLVED] Syncing a File Through iCloud in Swift


I am trying to give my iOS app the capability to sync the user’s data via iCloud. I Figured the way to go was to use iCloud Documents, as I already save/load a json file locally to store their data. However, I’m having trouble getting it working. I tried numerous tutorials online and none of them worked. Additionally, I cannot have the file visible to the user in their documents.
My latest code is based off this tutorial. Here is my current code, in my viewDidLoad:

    // check for container existence
    if let url = self.containerUrl, !FileManager.default.fileExists(atPath: url.path, isDirectory: nil) {
        print("does not exist")
        do {
            try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true, attributes: nil)
        catch {
    let documentUrl = self.containerUrl!.appendingPathComponent("test.txt")
    print("url: \(documentUrl)")
    let string = "Hello World!"
    do {
        //try string.write(to: documentUrl, atomically: true, encoding: .utf8)
        try print("Data: \(String(contentsOf: documentUrl))")
    catch {

I switch uncommenting the save and load lines for testing on different devices.

And here’s what I added to my info.plist:


and here’s my capabilities section:
My capabilities section in Xcode

So far, I am able to read and write to the file fine on one device, but on another device also signed in with my iCloud account, I get a file not found error:

The file “test.txt” couldn’t be opened because there is no such file.

I can see the file in my iCloud Drive (which I don’t want) on both devices, but I can only read it on the one I saved it with.

Any help or working tutorials on this subject would be appreciated.


Quit and re-open Xcode and build it again.

Answered By – JustMakeStuff

Answer Checked By – Gilberto Lyons (BugsFixing Admin)

Leave a Reply

Your email address will not be published.