Download PDF file and save in document directory

后端 未结 1 1851
栀梦
栀梦 2021-01-13 03:01

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

class ViewController: UIViewController {

    @IBOutlet weak          


        
1条回答
  •  旧巷少年郎
    2021-01-13 03:20

    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.

    Delegate method:

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

    Code to move the file:

    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.

    0 讨论(0)
提交回复
热议问题