D_Byrne
D_Byrne

Reputation: 395

Save file in iCloud Drive Documents (user Access)

I want to save a PDF file in the iCloud Drive. The user should have access to the file over his iCloud Drive App.

At the moment I can save a file in the iCloud Drive but it is in a hidden directory.

struct DocumentsDirectory {
    static let localDocumentsURL: NSURL? =  FileManager.default.urls(for:     FileManager.SearchPathDirectory.documentDirectory, in:     .userDomainMask).last! as NSURL
    static var url: NSURL? =   FileManager.default.url(forUbiquityContainerIdentifier: nil)! as NSURL
    static let iCloudDocumentsURL: NSURL? = url?.appendingPathComponent("Documents")! as! NSURL
}

With this code I get the hidden directory in the iCloud Drive (which is specific to my app).

Now my question is: can I save the file in the standard documents directory in the iCloud Drive? Or can I create a folder for the documents from my app, which the user can see?

Upvotes: 3

Views: 1471

Answers (1)

Rakshith Nandish
Rakshith Nandish

Reputation: 639

Try saving the file under the 'Documents' directory, this ensure the file is saved under the users public directory and is visible in the iCloud app as well.

func setupiCloudDriveForFileExport() {

    if let iCloudDocumentsURL = NSFileManager.defaultManager().URLForUbiquityContainerIdentifier(nil)?.URLByAppendingPathComponent("Documents") {
        if (!NSFileManager.defaultManager().fileExistsAtPath(iCloudDocumentsURL.path!, isDirectory: nil)) {
            do {
                try NSFileManager.defaultManager().createDirectoryAtURL(iCloudDocumentsURL, withIntermediateDirectories: true, attributes: nil)
            }catch let error as NSError {
                print(error)
            }
        }
    }
}

This code checks for the existance of the Documents directory on iCloud and if not creates a new one.

Upvotes: 2

Related Questions