我在"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"(以及其他一些),但收到不允许访问的错误。
我做错了什么?
在这里,您的pdf文件存储在应用程序的文档空间中。因此,您无法在"文件"应用中看到它。保存在应用程序文档文件夹中的每个文档都可以通过iTunes在文件共享中查看,但您需要先在Info.plist中添加权限:
- 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 文件共享
- LSS支持就地打开文档:支持就地打开文档
有关使用文件和UIDocumentInteractionController
的更多信息,您可以查看此博客文章。