IOS Swift 3 Copy file to iCloud Drive programmatically

In my option for uploading documents, I have. When users download documents from my app, I need to save them to iCloud Drive users that have already been installed on mobile devices. I have set up iCloud both online and in Xcode, but the problem is I can't copy files to iCloud Drive correctly. The file was uploaded successfully and is also being moved to iCloud, but the files will not show up in the iCloud Drive app. Here is my tested code:

<key>NSUbiquitousContainers</key>
    <dict>
        <key>iCloud.MyAppBundleIdentifier</key>
        <dict>
            <key>NSUbiquitousContainerIsDocumentScopePublic</key>
            <true/>
            <key>NSUbiquitousContainerName</key>
            <string>iCloudDriveDemo</string>
            <key>NSUbiquitousContainerSupportedFolderLevels</key>
            <string>Any</string>
        </dict>
    </dict>

      

And here is my iCloud storage code:

func DownloadDocumnt()
    {
        print("Selected URL: \(self.SelectedDownloadURL)")
        let fileURL = URL(string: "\(self.SelectedDownloadURL)")!

        let documentsUrl:URL =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL!
        let destinationFileUrl = documentsUrl.appendingPathComponent("Libra-\(self.SelectedDownloadFileName)")

        let sessionConfig = URLSessionConfiguration.default
        let session = URLSession(configuration: sessionConfig)

        let request = URLRequest(url:fileURL)

        let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in
            if let tempLocalUrl = tempLocalUrl, error == nil
            {
                if let statusCode = (response as? HTTPURLResponse)?.statusCode
                {
                    print("Successfully downloaded. Status code: \(statusCode)")
                }
                do
                {
                    if(FileManager.default.fileExists(atPath: destinationFileUrl.path))
                    {
                        try FileManager.default.removeItem(at: destinationFileUrl)
                        try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl)
                    }
                    else
                    {
                        try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl)
                    }

                    if let iCloudDocumentsURL = FileManager.default.url(forUbiquityContainerIdentifier: nil)?.appendingPathComponent("Documents")
                    {

                        if(!FileManager.default.fileExists(atPath: iCloudDocumentsURL.path, isDirectory: nil))
                        {
                            try FileManager.default.createDirectory(at: iCloudDocumentsURL, withIntermediateDirectories: true, attributes: nil)
                        }
                    }

                    let iCloudDocumentsURL = FileManager.default.url(forUbiquityContainerIdentifier: nil)?.appendingPathComponent("Documents").appendingPathComponent("Libra-\(self.SelectedDownloadFileName)")

                    if let iCloudDocumentsURL = iCloudDocumentsURL
                    {
                        var isDir:ObjCBool = false
                        if(FileManager.default.fileExists(atPath: iCloudDocumentsURL.path, isDirectory: &isDir))
                        {
                            try FileManager.default.removeItem(at: iCloudDocumentsURL)
                            try FileManager.default.copyItem(at: tempLocalUrl, to: iCloudDocumentsURL)
                        }
                        else
                        {
                            try FileManager.default.copyItem(at: destinationFileUrl, to: iCloudDocumentsURL)
                        }
                    }

                }
                catch (let writeError)
                {
                    print("Error creating a file \(destinationFileUrl) : \(writeError)")
                }
            }
            else
            {
                print("Error took place while downloading a file. Error description");
            }
        }
        task.resume()
    }

      

+3


source to share


2 answers


One of the most helpful articles when I came across this problem was the following link:

Technical Q&A QA1893 Updating iCloud Containers Metadata for iCloud Drive



I also removed and re-added entries in info.plist VERY CAREFULLY. This is what seemed to work. First, I copied and pasted the records from the online resource. It seems that the keys were not entirely accurate or contained hidden characters that could not be recognized.

Enabling document storage in iCloud Drive

+4


source


You cannot see files directly in the iCloud Drive app if the file is stored inside your iCloud App container.

    let iCloudDocumentsURL = FileManager.default.url(forUbiquityContainerIdentifier: nil)?.appendingPathComponent("Documents")

      



When you save a file to iCloud using the UbiquityContainerIdentifier path, it saves the file inside your iCloud App container. The App container is protected and cannot be viewed directly in iCloud Drive.

But we can see it through Settings -> click on your iCloud -> iCloud -> iCloud -> Manage storage -> your app name ->

+3


source







All Articles