I have an xcode application where i use a webview. At some point i can open a page with a link inside it. When i click on the link i should be able to download a pdf file. When i click on the link in the web browser it works and i download the file to my computer. But when i use my xcode application and access the web site in a webview, clicking on the link does not work.
I tried the piece of code below to download the file
// This method is called when any navigation action occurs in the web view
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
// Check if the navigation action is a link click
if navigationAction.navigationType == .linkActivated {
// Check if the link points to a PDF file
if let url = navigationAction.request.url, url.absoluteString.lowercased().hasSuffix(".pdf") {
// If it's a PDF file, initiate the download
downloadPDF(url: url)
// Cancel the navigation so that the PDF doesn't open in the web view
decisionHandler(.cancel)
return
}
}
// Allow other navigation actions to proceed
decisionHandler(.allow)
}
// Function to handle PDF download
func downloadPDF(url: URL) {
// You can use URLSession to download the PDF
let task = URLSession.shared.downloadTask(with: url) { localURL, urlResponse, error in
guard let localURL = localURL else {
if let error = error {
print("Download error: (error)")
}
return
}
// Move the downloaded file to a permanent location if needed
let destinationURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent(url.lastPathComponent)
do {
try FileManager.default.moveItem(at: localURL, to: destinationURL)
print("Downloaded PDF saved to: (destinationURL)")
// Handle the downloaded PDF file as needed, e.g., display it or provide options to open it
} catch {
print("File move error: (error)")
}
}
task.resume()
}
I ran the application in my xcode simulator. And destinationUrl showed a directory folder in devices folder of my xcode application. I am not sure if this is the problem but i can not run my app in a real device. So i can’t be sure of it.
Even though i can see the message “Downloaded PDF saved to (destinationURL)” message, when i look at my files i don’t see a file there. Is there a way to download the pdf file or is this problem occurs because i run the app in simulator ? Does anybody know how to solve this problem ?