NSURL使用Swift 3.0返回nil

时间:2016-11-16 05:31:45

标签: swift3 nsurl

使用Swift 2.3运行此代码时,很好。当我开始更新Swift 3的代码时,问题就开始了。当我使用下面的代码时,我的NSURL返回零:

{

var searchResults: [String]!

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let correctedAddress = self.searchResults[indexPath.row].addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)        
let urlpath:NSString! = "https://maps.googleapis.com/maps/api/geocode/json?address=\(correctedAddress)" as NSString!
let url = NSURL.init(string: urlpath as String)

}

 }           

我对iOS编程很新,所以我的问题可能非常基础。我用Google搜索了很多但找不到答案。

1 个答案:

答案 0 :(得分:0)

在Swift中,语法有很多变化,你可以像这样制作你的URL: -

let correctedAddress = "Delhi " //You can replace your address here
let urlpath = "https://maps.googleapis.com/maps/api/geocode/json?address=\(correctedAddress)".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
let url = URL(string: urlpath!)
print(url!)

结果: - https://maps.googleapis.com/maps/api/geocode/json?address=Delhi%20