URL 升级到 swift 3.0 后为零

URL nil after upgrade to swift 3.0

URL 转换为 swift 3.0

后为零

我的 swift2 代码(此代码完美运行)

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

我的swift转换后的3个代码

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

试图查看此处的问题。

var url : NSString = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=\(self.latitud‌​e),\(self.longitude)&destinations=\(self.stringForDistance)&language=en-US" 
var urlStr : NSString = url.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)! 
var searchURL : NSURL = NSURL(string: urlStr)! 
println(searchURL)

但是,我仍然可以找出 NSUTF8StringEncoding,因为它发生了错误

试试这个:

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)
}

试试这个

if let address = firstResult.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),
        let url = URL(string: "https://maps.googleapis.com/maps/api/geocode/json?address=\(address)") {
        print(url)
    }