iOS访问File app,打开手机和iCloud云盘文件

直接使用系统提供的文件api,不需要配置iCloud权限
模拟器不能选择文件,需要使用真机

上代码:

import UIKit
///调用系统api,打开FilePicker对话窗
func openFile(){
    let controller:UIDocumentPickerViewController
    if #available(iOS 14.0, *) {
        controller = UIDocumentPickerViewController(forOpeningContentTypes: [.pdf])
        controller.shouldShowFileExtensions = true
    } else {
        ///此处的字符串,可以查看iOS14中枚举注释中的UIT.
        ///如:
        /**
            An Adobe PDF document.
    
            **UTI:** com.adobe.pdf
    
            **conforms to:** public.data, public.composite-content

            public static var pdf: UTType { get }
        */
        controller = UIDocumentPickerViewController(documentTypes: ["com.adobe.pdf"], in: .open)
    }
    controller.delegate = self
    self.present(controller, animated: true)
}

///实现UIDocumentPickerDelegate代理
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
    ///读取文件之前需要先获取读取文件的授权
    if let url = urls.first,url.startAccessingSecurityScopedResource(){
        defer{
            ///释放权限
            url.stopAccessingSecurityScopedResource()
        }
        do {
            let data = try Data(contentsOf: url)
            ///todo:use data from file

        } catch let e{
            print(e)
        }
    }
}

你可能感兴趣的:(iOS访问File app,打开手机和iCloud云盘文件)