Evaldas Paulauskas

iOS developer professionally, hobbyist gamedev

Downloading a temporary PDF from URL for displaying in WebView

01 Sep 2020 » swift, iOS

At work had to download and display an invoice in pdf format if user so chooses to. Perhaps this will be useful to somebody, as there were no “clear” guides out there. And if you didn’t know yet, then for a WKWebview to open a .PDF file, you actually need to download it locally, else it will not open.

func downloadPdfIntoTemp(completionHandler: @escaping (URL) -> Void ) {   

    // Create Temp directory/filename + assign .pdf so webview reads it correct later
    let temporaryDirectoryURL = URL(fileURLWithPath: NSTemporaryDirectory(),
    isDirectory: true)
    let temporaryFilename = "\(ProcessInfo().globallyUniqueString).pdf"
    let temporaryFileURL =
        temporaryDirectoryURL.appendingPathComponent(temporaryFilename)

    // Create destination closure for Alamofire. Will automatically save the file to set URL here
    let destination: DownloadRequest.Destination = { _, _ in
        return (temporaryFileURL, [.createIntermediateDirectories, .removePreviousFile])
    }

    // Dummy URL, make sure its https, inject from outside in real use
    guard let url = URL(string: "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf") else { return }
    let request = URLRequest(url: url)

    AF.download(request, to: destination).downloadProgress { (progress) in
        print("\([progress.fractionCompleted])")
    }.response { response in
        guard let absUrl = response.fileURL?.absoluteURL else { return }
        print(absUrl)
        
        // Returning URL data type, so webView can instantly load it without any conversions required
        completionHandler(absUrl)
    }
}

Related Posts