thura oo thura oo - 8 days ago 5
Swift Question

Download PDF, saving to document directory and loading it in UIWebView

I am having problem with download pdf, saving to document directory and loading it in web view.
I have no experience with download things, saving things to directories and UIWebView before.

Before I ask this question, I've search multiple StackOverflow question and tried my best but it still doesn't work.

First This is how I download the PDF from url and save it to document directory

let myURL = URL(string: "https://example/example/product.pdf")
let urlRequest = NSURLRequest(url: myURL!)

do {
let theData = try NSURLConnection.sendSynchronousRequest(urlRequest as URLRequest, returning: nil)
var docURL = (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)).last as? NSURL
docURL = docURL?.appendingPathComponent("my.pdf") as NSURL?
try theData.write(to: docURL as! URL)
print("downloaded")
} catch (let writeError) {
print("error : \(writeError)")
}


The application pauses for a while and prints "downloaded"

This is how I check the list of contacts in my document directory

let docURL = (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last)
do{
let contents = try (FileManager.default.contentsOfDirectory(at: docURL!, includingPropertiesForKeys: nil, options: FileManager.DirectoryEnumerationOptions.skipsHiddenFiles))
print("There are")
print(contents)
}
catch (let error)
{
print("error contents \(error)")
}


It prints "There are [file:///private/var/mobile/Containers/Data/Application/DF6A310C-EB7E-405E-9B1B-654486B5D03A/Documents/my.pdf]"

This is how I load the pdf into webView

var webView = UIWebView(frame : vc.view.frame)
webView.scalesPageToFit = true
var paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
var documentsDirectory = paths[0]
var filePath = URL(fileURLWithPath: documentsDirectory).appendingPathComponent("my.pdf").absoluteString
var targetURL = URL(fileURLWithPath: filePath)
var request = URLRequest(url: targetURL)
webView.loadRequest(request)
vc.view.addSubview(webView)


The WebView comes up but shows nothing. I'm really confused if my.pdf is really saved with readable PDF format.

I don't know if there are some stuffs like I have to add something in info.plist or enable something in app capabilities. Thank you very much.

Answer

I didn't look through all of the code but the following two lines are a problem:

var filePath = URL(fileURLWithPath: documentsDirectory).appendingPathComponent("my.pdf").absoluteString
var targetURL = URL(fileURLWithPath: filePath)

The value of URL absoluteString does not give you a file path so the value of filePath is not a valid value for the URL fileURLWithPath: initializer.

And what's the point of going from URL to String (as a path) and back to a URL? Simply combine those two lines into:

var targetURL = URL(fileURLWithPath: documentsDirectory).appendingPathComponent("my.pdf")

As a side note, use some consistency. In other code you get the Documents folder URL using:

let docURL = (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last)

and in other code you use:

var paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
var documentsDirectory = paths[0]
var ... = URL(fileURLWithPath: documentsDirectory)...

Pick one approach and use it consistently. Since you need a URL, use the first approach. This means the code I suggested should now be:

let docURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last!
let targetURL = docURL.appendingPathComponent("my.pdf")