Mastering Development

How to download .icloud files in folder accessed via UIDocumentPickerViewController?

I’m trying to use UIDocumentPickerViewController to get access to all files within an iCloud directory as described in this Apple documentation.

let documentPicker = UIDocumentPickerViewController(documentTypes: [kUTTypeFolder as String], in: .open)
documentPicker.delegate = self
present(documentPicker, animated: true, completion: nil)
extension FileViewController: UIDocumentPickerDelegate {
    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
        guard let url = urls.first else { return }
        guard url.startAccessingSecurityScopedResource() else { return }
        defer { url.stopAccessingSecurityScopedResource() }

        var error: NSError? = nil
        NSFileCoordinator().coordinate(readingItemAt: url, error: &error) { (url) in
            let keys : [URLResourceKey] = [.nameKey, .isDirectoryKey]
            guard let fileList = FileManager.default.enumerator(at: url, includingPropertiesForKeys: keys) else { return }

            for case let file as URL in fileList {
                guard file.startAccessingSecurityScopedResource() else { continue }
                print(file.lastPathComponent) // Prints ".my_file_name.jpg.icloud"
                let newFileName = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("testfile.jpg")
                let data = try! Data(contentsOf: file)
                try! data.write(to: newFileName)

See my comment in the code above. The files in the directory are unsynced .icloud files. How do I force them to sync to the device, or access their actual contents?

Leave a Reply

Your email address will not be published. Required fields are marked *