下载PDF文件并保存在文档目录中 [英] Download PDF file and save in document directory

查看:155
本文介绍了下载PDF文件并保存在文档目录中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following code that allows me to download a PDF file from a URL, it works correctly:

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/Documents/

这个想法是,保存在该目录中的文件可用于离线读取(使用PDFKit或webKit).只有在删除应用程序后,它才会被删除.

The idea is that the file saved in that directory can be used to read it offline (with PDFKit or webKit). It will only be deleted if the application is deleted.

推荐答案

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

You need to move the file to your custom location after the download. Implement URLSessionDownloadDelegate and you will receive the location of your downloaded file.

代理方法:

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)")
}

要了解更多信息,请参考此存储库.

To learn more refer to this repo.

这篇关于下载PDF文件并保存在文档目录中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆