Search code examples
iosswiftxcodeicloud

Swift - saving a file to icloud drive


I am trying to save a file to iCloud with the following code in my iOS app:

        if let containerUrl = FileManager.default.url(forUbiquityContainerIdentifier: nil)?.appendingPathComponent("Documents") {
        if !FileManager.default.fileExists(atPath: containerUrl.path, isDirectory: nil) {
            do {
                try FileManager.default.createDirectory(at: containerUrl, withIntermediateDirectories: true, attributes: nil)
            }
            catch {
                print(error.localizedDescription)
            }
        }
        
        let fileUrl = containerUrl.appendingPathComponent("test.txt")
        do {
            let accData = String(data: NSData.init(contentsOf: file.fileURL)! as Data, encoding: String.Encoding.utf8)!
            print(accData)
            DispatchQueue.main.async {
                try? accData.data(using: .utf8)?.write(to: fileUrl)

            }
            
        }
        catch {
            print(error.localizedDescription)
        }
    }

fileUrl looks as follows "file:///private/var/mobile/Library/Mobile%20Documents/iCloud~project~iCloud/Documents/". On the Phone under Settings -> iCloud -> Manage Data there is a new dir caled iCloud (see screenshot):

enter image description here

and when going into the dir i can see my saved file: enter image description here

How can I save it into "iCloud Drive" instead so it is also visible from other locations?


Solution

  • I resolved the issue by naming the icloud bucket with the same name as bundle id of the app -> then upgrading the version number of the app