I am trying to convert a String to NSURL and my code for that is Below:
var url = \"https://maps.googleapis.com/maps/api/distancema
SWIFT 3.0
A safe way to fix a bad string being converted to NSURL is by unwrapping the urlPath string variable using "guard let"
guard let url = NSURL(string: urlPath.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)
else
{
print("Couldn't parse myURL = \(urlPath)")
return
}
The variable called "urlPath" in my above example would be the url string you have already declared somewhere else in your code.
I came across this answer because randomly I was getting the nil error with XCode breaking at the point my string was made into a NSURL. No logic as to why it was random even when I printed the url's they would look fine. As soon as I added the .addingPercentEncoding it was back working without any issues whatsoever.
tl;dr For anyone reading this, try my above code and swap out "urlPath" for your own local string url.