【问题标题】:URL nil after upgrade to swift 3.0升级到 swift 3.0 后的 URL 为零
【发布时间】:2017-01-25 04:02:24
【问题描述】:

隐蔽到 swift 3.0 后 URL 为零

我的 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

试图在这里查看问题。 Convert String to NSURL is return nil in swift

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 因为它发生错误

【问题讨论】:

    标签: url nsurlsession nsurl swift3 nsurlsessiondatatask


    【解决方案1】:

    试试这个:

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

    【讨论】:

    • CharacterSet.urlQueryAllowed
    • 因为字符串没有意义
    【解决方案2】:

    试试这个

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-25
      • 2013-08-18
      相关资源
      最近更新 更多