Mario Burga
Mario Burga

Reputation: 1157

Download PDF file and save in document directory

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

The file is currently going to: 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

How do I save it in /Documents/?

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

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.

Upvotes: 6

Views: 10377

Answers (2)

Alex - Exaland Concept
Alex - Exaland Concept

Reputation: 127

This snippet was downloaded your Remote PDF from Server and "Save" into your Photo Library

   func drawPDFfromURL(url: URL) -> UIImage? {
    guard let document = CGPDFDocument(url as CFURL) else { return nil }
    guard let page = document.page(at: 1) else { return nil }

    let pageRect = page.getBoxRect(.mediaBox)
    let renderer = UIGraphicsImageRenderer(size: pageRect.size)
    let img = renderer.image { ctx in
        UIColor.white.set()
        ctx.fill(pageRect)

        ctx.cgContext.translateBy(x: 0.0, y: pageRect.size.height)
        ctx.cgContext.scaleBy(x: 1.0, y: -1.0)

        ctx.cgContext.drawPDFPage(page)
    }

    return img
}

step 2

 UIImageWriteToSavedPhotosAlbum(drawPDFfromURL(url: url!) ?? UIImage(), nil, nil, nil)

Upvotes: 0

Sharad Chauhan
Sharad Chauhan

Reputation: 4891

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.

Upvotes: 6

Related Questions