我查找了有关“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 上的"file"文件夹下,并且找不到访问它的方法。 打印出来的文件 url 如下所示:
file:///var/mobile/Containers/Data/Application/635B2D57-CA7B-44EF-BDF1-4308CABD8ED5/Documents/doc.pdf
我尝试将其写入“.downloadsDirectory”(以及其他一些目录),但收到不允许访问的错误。
我做错了什么?
最佳答案
此处,您的 pdf 文件存储在应用程序的文档空间内。因此您无法在文件应用程序中看到它。保存在应用程序的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:支持就地打开文档
有关使用Files和UIDocumentInteractionController
的更多信息,您可以查看此blog post .
关于ios - 在 iPhone 上的 "files"目录中找不到保存的 pdf文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53989929/