6

In my I'm having documents download option. When users downloading documents from my app I need to store it to users iCloud Drive which was install in users mobile already. I have configured iCloud in both web and in Xcode, but problem is I'm not able to copy files to iCloud Drive correctly. File was downloaded successfully, and also it moving to iCloud but files won't appearing in iCloud Drive App. Here is my tried 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()
    }
Kavin Kumar Arumugam
  • 1,792
  • 3
  • 28
  • 47
  • Does you app's folder show up in iCloud Drive (the app or finder)? – John D. May 25 '17 at 14:05
  • @JohnD. No it won't show up anywhere else. But we can see it through Settings -> Storage&iCloudUsage -> iCloud Manage Settings. – Kavin Kumar Arumugam May 26 '17 at 05:18
  • try this solution https://stackoverflow.com/a/50397424/2171764 – Jhonattan May 17 '18 at 17:38
  • Hello @KavinKumarArumugam i am using your code to upload file using URL and i am getting this Error can you help me in this "{Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}" – Hardik Vyas Jul 04 '18 at 08:29
  • @hardikvyas please check once there is space between your file path URL before saving. if there is any space replace it by "%20". For Example: `self.destinationFileUrl = self.destinationFileUrl.replacingOccurrences(of: " ", with: "%20")` – Kavin Kumar Arumugam Jul 04 '18 at 08:51

2 Answers2

12

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

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

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

But we can see it through Settings -> click on Your iCloud -> iCloud -> iCloud -> Manage Storage -> your App Name ->

Ranjith
  • 425
  • 6
  • 8
  • So, fetching file list from icloud is not possible ? To download a file from icloud, we must know the file name , right ? – Jamshed Alam Dec 03 '19 at 07:44
6

One of the most useful articles when I was having this issue was at the following link:

Technical Q&A QA1893 Updating the metadata of iCloud containers for iCloud Drive

I also deleted and re-added my info.plist entries VERY CAREFULLY. That is what seemed to work. I originally copied and pasted the entries from an online resource. It seems that the keys were not exactly correct or contained some hidden characters which caused them not to be recognized.

Enabling Document Storage in iCloud Drive

John D.
  • 548
  • 7
  • 19
  • 1
    I can get the files I've created programatically in the iOS app, but I can't make them visible on iCloud Drive. I've tried the steps in those two links repeatedly, but nothing shows up on my iCloud Drive on my Mac or on the web or on the Files app in iOS. – adamek Apr 04 '20 at 13:58
  • @adamek Did you ever figure this out? – daniel Sep 02 '23 at 07:06