ios - 下载PDF文件并保存在文档目录中

标签 ios swift xcode pdf remote-server

我有以下代码允许我从 URL 下载 PDF 文件,它工作正常:

class ViewController: UIViewController {

    @IBOutlet weak var progressView: UIProgressView!

    override func viewDidLoad() {
        let _ = DownloadManager.shared.activate()
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        DownloadManager.shared.onProgress = { (progress) in
            OperationQueue.main.addOperation {
                self.progressView.progress = progress
            }
        }
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        DownloadManager.shared.onProgress = nil
    }

    @IBAction func startDownload(_ sender: Any) {
        let url = URL(string: "https://d0.awsstatic.com/whitepapers/KMS-Cryptographic-Details.pdf")!
        let task = DownloadManager.shared.activate().downloadTask(with: url)
        task.resume()
    }
}

该文件当前位于:file:///Users/cybermac/Library/Developer/CoreSimulator/Devices/CAEC75D0-423A-4FB2-B0D6-9E7CADB190A1/data/Containers/Data/Application/8B5CBFC8- 7058-48DB-A1C4-872302A80610/Library/Caches/com.apple.nsurlsessiond/Downloads/com.example.DownloadTaskExample/CFNetworkDownload_Q7OVlf.tmp

如何保存到/Documents/

像这样:file:///Users/cybermac/Library/Developer/CoreSimulator/Devices/CAEC75D0-423A-4FB2-B0D6-9E7CADB190A1/data/Containers/Data/Application/64370B29-2C01-470F -AE76-17EF1A7BC918/文档/

想法是保存在该目录中的文件可用于离线阅读(使用 PDFKit 或 webKit)。仅当应用程序被删除时它才会被删除。

最佳答案

您需要在下载后将文件移动到您的自定义位置。实现 URLSessionDownloadDelegate,您将收到下载文件的位置。

委托(delegate)方法:

func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL)

移动文件的代码:

do {
    let documentsURL = try
        FileManager.default.url(for: .documentDirectory,
                                in: .userDomainMask,
                                appropriateFor: nil,
                                create: false)

    let savedURL = documentsURL.appendingPathComponent("yourCustomName.pdf")
    try FileManager.default.moveItem(at: location, to: savedURL)
} catch {
    print ("file error: \(error)")
}

要了解更多信息,请参阅 this repo .

关于ios - 下载PDF文件并保存在文档目录中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51374225/

相关文章:

ios - UITextView - 设置字体不适用于 XCode 5 上的 iOS 6

iPhone 辅助功能 旁白

ios - Xcode 6.1 - 标签上的属性文本不显示自定义字体

ios - 根据字体大小将文本滚动到 UITextView 中的特定点

iphone - 将对象添加到多个 View

ios - 如何使用 PlistBuddy 添加设置而不覆盖现有设置?

ios - UIViewController 覆盖

ios - UITextField inputView 显示撤消、重做、粘贴按钮

ios - 升级后 Alamofire 不工作(Swift/Xcode 8)

swift - 我无法在调试器中看到变量的值