我正在尝试将转换为String,NSURL而我的代码如下:
String
NSURL
var url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=\(self.latitude),\(self.longitude)&destinations=\(self.stringForDistance)&language=en-US" println("This is String: \(url)") var remoteUrl : NSURL? = NSURL(string: url) println("This is URL: \(remoteUrl)")
控制台会打印如下内容:
This is String: https://maps.googleapis.com/maps/api/distancematrix/json?origins=-34.4232722,150.8865837&destinations=-34.4250728,150.89314939999997|-34.4356434,150.8858692|-34.4250728,150.89314939999997|-34.4356434,150.8858692|-34.4250728,150.89314939999997|-34.4356434,150.8858692|-34.423234,150.88658899999996|-34.423234,150.88658899999996|-34.428251,150.899673|-34.4257439,150.89870229999997|-34.423234,150.88658899999996|-34.4257439,150.89870229999997|-34.425376,150.89388299999996&language=en-US This is URL: nil
的remoteUrl是nil,我不知道这里有什么问题。
remoteUrl
nil
之后,我尝试String像这样进行排序:
var url : String = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=-34.4232722,150.8865837&destinations=-34.4250728,150.89314939999997&language=en-US" println("This is String: \(url)") var remoteUrl : NSURL? = NSURL(string: url) println("This is URL: \(remoteUrl)")
和控制台打印:
This is String: https://maps.googleapis.com/maps/api/distancematrix/json?origins=-34.4232722,150.8865837&destinations=-34.4250728,150.89314939999997&language=en-US This is URL: Optional(https://maps.googleapis.com/maps/api/distancematrix/json?origins=-34.4232722,150.8865837&destinations=-34.4250728,150.89314939999997&language=en-US)
一切正常。
那么,有人可以告诉我我的第一个案例有什么问题吗?
正如Martin R所建议的,我看到了这篇文章,并将那个Objective- C代码转换为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)
并且这正常工作。
对于Swift 3.0:
let url : NSString = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=\(self.latitude),\(self.longitude)&destinations=\(self.stringForDistance)&language=en-US" let urlStr : NSString = url.addingPercentEscapes(using: String.Encoding.utf8.rawValue)! as NSString let searchURL : NSURL = NSURL(string: urlStr as String)! print(searchURL)