1

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?

Henryk Borzymowski
  • 988
  • 1
  • 10
  • 22

2 Answers2

0

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

Henryk Borzymowski
  • 988
  • 1
  • 10
  • 22
  • I've done your exact steps and incremented the version number to 1.0.1 but still doesnt show in File app any ideas? https://stackoverflow.com/questions/76131000/cannot-save-files-to-icloud-drive-and-have-it-appear-in-file-app – erotsppa Apr 28 '23 at 15:24
-1

Documents is the directory of the documents visible to the user. Save the document to the Library instead:

if let containerUrl = FileManager.default.url(forUbiquityContainerIdentifier: nil)?.appendingPathComponent("Library") {
JustMakeStuff
  • 419
  • 3
  • 19