代码之家  ›  专栏  ›  技术社区  ›  pb4now

在iPhone的“文件”目录中找不到保存的pdfile

  •  0
  • pb4now  · 技术社区  · 6 年前

    我找了所有关于“so”的“save pdf file”问题,这时我的头撞在墙上,上面写着:

    我(从FireBase存储)下载了一个PDF文件,并尝试用该代码保存:

    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如下所示:

    文件:///var/mobile/containers/data/application/635b2d57-ca7b-44ef-bdf1-4308abd8ed5/documents/doc.pdf

    我试图将其写入“.downloadsdirectory”(以及其他一些目录),但得到的错误是不允许访问。

    我做错什么了?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Yannick Loriot    6 年前

    在这里,您的PDF文件存储在应用程序的文档空间中。所以你看不到 文件夹 应用程序。所有保存在 文件 您的应用程序的文件夹可以通过iTunes在 文件共享 但您需要在 幻灯片 第一:

    • 已启用ui文件共享 :应用程序支持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
        }
    }
    

    不要忘记将这些权限添加到 幻灯片 文件:

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

    有关使用 文件夹 ui文档交互控制器 你可以查一下这个 blog post .