Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save pdf document to iCloud Drive programmatically using swift?

My app creates a pdf file, and I want to save that pdf document to iCloud Drive programmatically using swift 3.

For a sample, here I used a Text file to save in iCloud Drive.

This is my code:

func copyDocumentsToiCloudDrive() {
    var error: NSError?
    let iCloudDocumentsURL = FileManager.default.url(forUbiquityContainerIdentifier: nil)?.appendingPathComponent("myCloudTest")

    do{
        //is iCloud working?
        if  iCloudDocumentsURL != nil {
            //Create the Directory if it doesn't exist
            if (!FileManager.default.fileExists(atPath: iCloudDocumentsURL!.path, isDirectory: nil)) {
                //This gets skipped after initial run saying directory exists, but still don't see it on iCloud
                try FileManager.default.createDirectory(at: iCloudDocumentsURL!, withIntermediateDirectories: true, attributes: nil)
            }
        } else {
            print("iCloud is NOT working!")
            //  return
        }

        if error != nil {
            print("Error creating iCloud DIR")
        }

        //Set up directorys
        let localDocumentsURL = FileManager.default.urls(for: FileManager.SearchPathDirectory.documentDirectory, in: .userDomainMask).last! as NSURL

        //Add txt file to my local folder
        let myTextString = NSString(string: "HELLO WORLD")
        let myLocalFile = localDocumentsURL.appendingPathComponent("myTextFile.txt")
        _ = try myTextString.write(to: myLocalFile!, atomically: true, encoding: String.Encoding.utf8.rawValue)

        if ((error) != nil){
            print("Error saving to local DIR")
        }

        //If file exists on iCloud remove it
        var isDir:ObjCBool = false
        if (FileManager.default.fileExists(atPath: iCloudDocumentsURL!.path, isDirectory: &isDir)) {
            try FileManager.default.removeItem(at: iCloudDocumentsURL!)
        }

        //copy from my local to iCloud
        if error == nil {
            try FileManager.default.copyItem(at: localDocumentsURL as URL, to: iCloudDocumentsURL!)
        }
    }
    catch{
        print("Error creating a file")
    }

}

This code is working without any errors. But not showing the saved file in iCloud Drive.

I refer this link and I wrote this code.

like image 758
anas.p Avatar asked Aug 27 '17 14:08

anas.p


1 Answers

Assuming your code works as intended, try updating the version and build number of your application in the info.plist. A change in these values are needed for the iCloud changes to reflect.

like image 81
Rakshith Nandish Avatar answered Oct 19 '22 15:10

Rakshith Nandish