Search code examples
iosswiftnsurl

How can I open a pdf link when click a button on Swift?


I am trying to open a pdf from my Swift application but I cannot make it to work.

I know that there are a lot of questions related with this and in most of them they use this code:

UIApplication.shared.openURL(URL(string: "http://www.url.com" + id)!)

But I am getting the following error:

fatal error: unexpectedly found nil while unwrapping an Optional value

so I thought that the error was because the id was nil so I made two prints to see what was retrieved: one for url and one for id. Both of them are correct and if I copy the url on the browser navigation bar it works perfectly (I cannot provide the real url because it is of a client).

I have this function wrapped inside an @IBAction to detect when a button is clicked so I looked if the connection had been broken. It is also correct.

So I cannot understand why this error is happening. I spent some hours but cannot figure out what is causing this error.

Am I missing something? Should I codify the url in some way?

P.S: I am using Xcode8 and Swift3.

UPDATE: If I set www.google.es it is working perfectly. Can it be a problem using variables inside of the url?

Thanks in advance!


Solution

  • Finally, after some hours searching about the problem and following the recommendation of @rmaddy (Thanks!) I have split my function in three parts and I could see that the URL was returning nil value.

    It was strange because I could copy the string into my browser navigation bar and it worked well so I thought that it could be something about encoding. One time I have encoded it I noticed that the id of the pdf was retrieved with a \r at the final of the id. Like this:

    id004.pdf\r
    

    The solution that I have done is the following:

    var string = "http://www.url.com" + id
    var index1 = string.index(string.endIndex, offsetBy: -1)
    var substring1 = string.substring(to: index1)
    
    let encodedString = substring1.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
    UIApplication.shared.openURL(NSURL(string: encodedString!) as! URL)
    

    Encoded string is necessary because if not the link no longer work.