【问题标题】:Saved pdfFile not found in "files" directory on iphone在iphone的“文件”目录中找不到保存的pdf文件
【发布时间】:2018-12-31 17:26:35
【问题描述】:

我在“SO”上查找了所有“保存 pdf 文件”的问题,而此刻,我把头撞到了墙上:

我下载了一个 pdf 文件(从 firebase 存储)并尝试使用该代码保存它:

static func getPdf(firebaseStoragePath:String){
    let ref = Storage.storage().reference().child(firebaseStoragePath)

    let documentsURL:NSURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! as NSURL
    let fileURL = documentsURL.appendingPathComponent("doc.pdf")
    print("***fileURL: ",fileURL ?? "")

    let task = ref.write(toFile: fileURL!)

    task.observe(StorageTaskStatus.success) { (snap) in
        print("success")
    }
}

似乎下载成功,但文件没有显示在我 iPhone 上的“文件”文件夹下,并且找不到访问它的方法。 打印出来的文件url是这样的:

file:///var/mobile/Containers/Data/Application/635B2D57-CA7B-44EF-BDF1-4308CABD8ED5/Documents/doc.pdf

我尝试将其写入“.downloadsDirectory”(以及其他一些),但出现不允许访问的错误。

我做错了什么?

【问题讨论】:

    标签: ios swift firebase-storage nsfilemanager


    【解决方案1】:

    在这里,您的 pdf 文件存储在应用程序的文档空间中。所以你不能在 Files 应用程序中看到它。保存在应用程序Document文件夹中的每个文档都可以通过iTunes在文件共享中查看,但您需要在Info.plist中添加权限em> 首先:

    • UIFileSharingEnabled:应用程序支持 iTunes 文件共享

    要将文档存储在文件中,您需要使用UIDocumentInteractionController 库:

    let documentInteractionController = UIDocumentInteractionController()
    
    func downloadPdf(firebaseStoragePath:String){
        let ref = Storage.storage().reference().child(firebaseStoragePath)
    
        let documentsURL: NSURL = FileManager.default.urls(for: .temporaryDirectory, in: .userDomainMask).first! as NSURL
        let fileURL = documentsURL.appendingPathComponent("doc.pdf")
    
        let task = ref.write(toFile: fileURL!)
    
        task.observe(StorageTaskStatus.success) { (snap) in
            DispatchQueue.main.async {
                documentInteractionController.url = documentsURL
                documentInteractionController.uti = documentsURL.typeIdentifier ?? "public.data, public.content"
                documentInteractionController.name = documentsURL.localizedName ?? url.lastPathComponent
                documentInteractionController.presentPreview(animated: true)
            }
        }
    }
    
    extension URL {
        var typeIdentifier: String? {
            return (try? resourceValues(forKeys: [.typeIdentifierKey]))?.typeIdentifier
        }
        var localizedName: String? {
            return (try? resourceValues(forKeys: [.localizedNameKey]))?.localizedName
        }
    }
    

    不要忘记在 Info.plist 文件中添加这些权限:

    • UIFileSharingEnabled:应用程序支持 iTunes 文件共享
    • LSSupportsOpeningDocumentsInPlace:支持就地打开文档

    有关使用文件UIDocumentInteractionController的更多信息,您可以查看blog post

    【讨论】:

    • 你是救世主先生 - Ty 非常 - 将立即测试 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-15
    • 1970-01-01
    • 1970-01-01
    • 2021-06-25
    • 1970-01-01
    相关资源
    最近更新 更多