App中添加打开iCloud选择文件功能

有时候app中需要从外部读取文件,并使用。在iOS中,并没有很开放的文件系统,一般只能通过iCloud。(app内置文件的话,每次文件更新,app也要更新,不建议使用)

那么该如何使用iCloud呢?这里就需要用到UIDocumentPickerViewController

UIDocumentPickerViewController有四种模式:

  • Import an external document:用户选择一个外部文档,文档选择器拷贝该文档到应用沙盒,不会修改源文档。
  • Export a local document:文档选择器拷贝文档到一个外部路径,不会修改源文档。
  • Open an external document:打开一个外部文档,用户可以修改该文档。
  • Move a local document:拷贝文档到外部路径,同时可以修改该拷贝。

知道了以上这些,那就好办了,上代码。

import UIKit

class ViewController: UIViewController, UIDocumentPickerDelegate {
    
    var filePath = ""

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.orange
        
        let btn = UIButton(frame: CGRect(x: 100, y: 200, width: 80, height: 40))
        btn.backgroundColor = UIColor.purple
        view.addSubview(btn)
        btn.addTarget(self, action: #selector(jumpToICloud), for: .touchUpInside)
        
        let btn2 = UIButton(frame: CGRect(x: 250, y: 200, width: 80, height: 40))
        btn2.backgroundColor = UIColor.green
        view.addSubview(btn2)
        btn2.addTarget(self, action: #selector(getFile), for: .touchUpInside)
    }
    
    @objc func jumpToICloud() {
        //打开iCloud文件界面
        let menuVc = UIDocumentPickerViewController(documentTypes: ["public.data","public.item",], in: .import)
        menuVc.modalPresentationStyle = .fullScreen
        menuVc.delegate = self
        present(menuVc, animated: true, completion: nil)
    }
    
    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
        print(urls)
        if let url = urls.first {
            filePath = url.absoluteString
            let error = NSErrorPointer(nil)
            let fileCoor = NSFileCoordinator()
            fileCoor.coordinate(readingItemAt: url, options: [], error: error) { fileUrl in
                //print(fileUrl)
                let fileName = fileUrl.lastPathComponent
                //print(fileName)
                do {
                    let data = try Data(contentsOf: fileUrl, options: .mappedRead)
                    let arr = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
                    let documentPath = arr.last
                    print(documentPath)
                    let localFileName = documentPath?.appending("/").appending(fileName) ?? ""
                    let desPath = URL(fileURLWithPath: localFileName)
                    try data.write(to: desPath, options: .atomic)
                    print(data.count)
                    filePath = localFileName
                } catch let error as Error? {
                    print(error?.localizedDescription)
                }
            }
        }
    }
    
    func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
        print("documentPickerWasCancelled")
    }
    
    @objc func getFile() {
        let url = URL(fileURLWithPath: filePath)
        // 带throws的方法需要抛异常
        do {
            /*
             * try 和 try! 的区别
             * try 发生异常会跳到catch代码中
             * try! 发生异常程序会直接crash
             */
            let data = try Data(contentsOf: url)
            //let jsonData:Any = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers)
            print(data.count)
            
        } catch let error as Error? {
            print(error?.localizedDescription)
        }
    }
}


需要注意的是,使用这个功能,必须登录iCloud。此外documentTypes的类型(["public.data","public.item"])必须是根据自己需要的来,否则即使文件传到iCloud中了,也无法访问。

另外,如果是open模式的,可能需要在info.plist文件中设置Application supports iTunes file sharing为YES以及Supports opening documents in place才能得到预期的结果。例如:url.startAccessingSecurityScopedResource()

demo地址

参考链接:
访问沙盒外文档UIDocumentPickerViewController

documentTypes官方参考文档

你可能感兴趣的:(App中添加打开iCloud选择文件功能)