URL is nil after covert to swift 3.0
my swift2 code (This code works prefect)
let correctedAddress:String! = firstResult.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.symbolCharacterSet())
let url = NSURL(string: "https://maps.googleapis.com/maps/api/geocode/json?address=\(correctedAddress)")
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) { (data, response, error) -> Void in
my swift 3 code after convert
print(firstResult)
let correctedAddress:String! = firstResult.addingPercentEncoding(withAllowedCharacters: CharacterSet.symbols)
print(correctedAddress)
let url = URL(string: "https://maps.googleapis.com/maps/api/geocode/json?address=\(correctedAddress)")
print(url)
let task = URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) -> Void in
San Francisco, California, United States
%53%61%6E%20%46%72%61%6E%63%69%73%63%6F%2C%20%43%61%6C%69%66%6F%72%6E%69%61%2C%20%55%6E%69%74%65%64%20%53%74%61%74%65%73
nil
Tried to look at the question in here. Convert String to NSURL is return nil in swift
var url : NSString = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=\(self.latitude),\(self.longitude)&destinations=\(self.stringForDistance)&language=en-US"
var urlStr : NSString = url.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
var searchURL : NSURL = NSURL(string: urlStr)!
println(searchURL)
But, I still could figure out the NSUTF8StringEncoding since it occurs an error
Try this:
let firstResult = "San Francisco, California, United States"
print(firstResult)
if let correctedAddress = firstResult.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),
let url = URL(string: "https://maps.googleapis.com/maps/api/geocode/json?address=\(correctedAddress)") {
print(url)
}