ios - 快速从url下载pdf并将其保存到文件中
问题描述
我正在从 url 下载 pdf 并保存到 .documentsDirectory。但它保存在应用程序数据中的某个地方,而不是我想将它保存在手机上。
func downnload(url: NSURL, filename:String) {
let fileName = String((url.lastPathComponent!)) as NSString
let documentsUrl:URL = (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL?)!
let destinationFileUrl = documentsUrl.appendingPathComponent("\(fileName)")
let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig)
let request = URLRequest(url:url as URL)
let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in
if let tempLocalUrl = tempLocalUrl, error == nil {
// Success
if let statusCode = (response as? HTTPURLResponse)?.statusCode {
print("Successfully downloaded. Status code: \(statusCode)")
}
do {
try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl)
do {
let contents = try FileManager.default.contentsOfDirectory(at: documentsUrl, includingPropertiesForKeys: nil, options: .skipsHiddenFiles)
for indexx in 0..<contents.count {
if contents[indexx].lastPathComponent == destinationFileUrl.lastPathComponent {
let activityViewController = UIActivityViewController(activityItems: [contents[indexx]], applicationActivities: nil)
self.present(activityViewController, animated: true, completion: nil)
}
}
}
catch (let err) {
print("error: \(err)")
}
} catch (let writeError) {
print("Error creating a file \(destinationFileUrl) : \(writeError)")
}
} else {
print("Error took place while downloading a file. Error description: \(error?.localizedDescription ?? "")")
}
}
task.resume()
}
}
解决方案
您可以使用 UIDocumentInteractionController 将文件保存到 Apple 的文件应用程序中
从 url 下载 pdf 并保存到 .documentsDirectory 后,将您的 documentsDirectory 文件 url 提供给 UIDocumentInteractionController
let documentInteractionController = UIDocumentInteractionController()
documentInteractionController.url = url //Here is your documentsDirectory file url
documentInteractionController.uti = url.typeIdentifier ?? "public.data, public.content"
documentInteractionController.name = url.localizedName ?? url.lastPathComponent
documentInteractionController.presentOptionsMenu(from: view.frame, in: view, animated: true)
在这里,我使用 URL 的扩展名
extension URL {
var typeIdentifier: String? {
return (try? resourceValues(forKeys: [.typeIdentifierKey]))?.typeIdentifier
}
var localizedName: String? {
return (try? resourceValues(forKeys: [.localizedNameKey]))?.localizedName
}
}
推荐阅读
- mysql - knex 迁移失败,但不恢复更改
- vue.js - 在 Vuex 操作中直接操作状态与使用 'commit' 和 'getters'
- nlp - 使用 SimLex-999 和 wordsim 评估 word2vec - 关键错误
- assembly - 用于 arm 架构的最新内核代码在 slow_work_pending 是否错误?
- flask - 模块“请求”没有属性“文件”
- c - 如何从 SQlite3 中的 SQL 表中删除多个列?
- windows - 通过批处理脚本的命令窗口在执行后没有停止
- javascript - 在 PrimeNG exprot 中将客户列添加为 CSV
- c# - 列出或发现单元测试未涵盖的方法
- blockchain - Hyperledger Sawtooth 区块链中的默认和最大块大小是多少