在我的一个应用程序中,我需要对地址字符串进行地理编码。起初我考虑使用CLGeocoder
。但是,在我尝试之后,我偶然发现了我在this问题中描述的问题。
解决方案是使用Google的地理编码API。我现在已切换到它们并通过具有以下功能设法使它们工作:
func startConnection(){
self.data = NSMutableData()
let urlString = "https://maps.googleapis.com/maps/api/geocode/json?address=\(searchBar.text!)&key=MYKEY"
let linkUrl:NSURL = NSURL(string:urlString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!)!
let request: NSURLRequest = NSURLRequest(URL: linkUrl)
let connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)!
connection.start()
}
func connection(connection: NSURLConnection!, didReceiveData data: NSData!){
self.data.appendData(data)
}
func connectionDidFinishLoading(connection: NSURLConnection!) {
do {
if let json = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as? [String: AnyObject] {
print(json)
}
}
catch {
print("error1")
}
}
这很有效,解决了CLGeocoder
带来的问题。但是,除了提取地点坐标外,我还需要使用Google的Timezone API来提取每个地方的时区。
使用NSURLConnection
或NSURLSession
执行此操作在我看来有点困难,因为我需要跟踪哪个会话/连接返回。所以,我想有一些使用完成处理程序的解决方案。
我尝试过使用Alamofire框架(使用Swift 2.0的正确分支)。但是,在这种情况下,似乎request()
函数是错误的。我试过了:
let parameters = ["address":searchBar.text!,"key":"MYKEY"]
Alamofire.request(.GET, "https://maps.googleapis.com/maps/api/geocode/json", parameters: parameters).responseJSON(options:.AllowFragments) { _, _, JSON in
print(JSON)
}
我打印的所有内容都是" SUCCESS"。我希望我做错了,它可以修复,因为我真的希望能够使用闭包而不是委托调用。
我的问题是:
NSURSession
或NSURLConnection
s的系统,这样我就可以为每次通话而不是代表使用完成处理程序?P.S。我知道我可以使用同步请求,但我真的想避免使用该选项
有人建议,添加.MutableContainers
作为选项应该responseJSON
有效。我尝试了下面的代码:
let apiKey = "MYKEY"
var parameters = ["key":apiKey,"components":"locality:\(searchBar.text!)"]
Alamofire.request(.GET, "https://maps.googleapis.com/maps/api/geocode/json", parameters: parameters).responseJSON(options:.MutableContainers) { one, two, JSON in
print(JSON)
}
我打印的所有内容都是" SUCCESS"。
答案 0 :(得分:-1)
好的,我终于弄明白了(在@cnoon的帮助下)。返回的值是Result
类型。我找不到相关文档,但源代码可用here。
为了检索JSON,可以使用以下实现:
Alamofire.request(.GET, "https://mapss.googleapis.com/maps/api/geocode/json", parameters: parameters).responseJSON(options:.MutableContainers) { _, _, JSON in
switch JSON {
case .Failure(_, let error):
self.error = error
break
case .Success(let value):
print(value)
break
}
}
打印的value
是地理编码API响应的正确表示。