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

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

作者: ufogxl | 来源:发表于2022-07-17 20:01 被阅读0次

直接使用系统提供的文件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云盘文件

      本文链接:https://www.haomeiwen.com/subject/jztyprtx.html