代码之家  ›  专栏  ›  技术社区  ›  Mario Burga

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

  •  4
  • Mario Burga  · 技术社区  · 6 年前

    我有以下代码可以从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

    如何将其保存在/文档中/

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

    其思想是,保存在该目录中的文件可以用于脱机读取(使用pdfkit或webkit)。只有在删除应用程序时才会删除。

    1 回复  |  直到 6 年前
        1
  •  4
  •   Sharad Chauhan Muhammad Bilal Hussain    6 年前

    URLSessionDownloadDelegate

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

    https://github.com/skdevil/PrakrstaFileDownloader