Alamofire与谷歌地理编码API

在我的一个应用程序中,我需要对地址string进行地理编码。 起初我考虑使用CLGeocoder 。 但是,在我尝试过之后,我偶然发现了一个我在这个问题中所描述的问题。

解决scheme是使用Google的Geocoding API。 我现在已经切换到他们,并设法通过以下function让他们工作:

 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来提取每个地点的时区。

这样做与NSURLConnectionNSURLSession似乎有点困难,因为我需要跟踪哪个会话/连接返回。 所以,我想有一些使用完成处理程序的解决scheme。

我试过使用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) } 

而我印的是“成功”。 我希望我做错了什么,它可以被修复,因为我真的希望能够使用闭包,而不是委托调用。

我的问题是:

  1. Google地理编码API可以使用Alamofire吗?
  2. 如果是这样,你能告诉我我做错了什么吗?
  3. 如果这是不可能的,你可以请我build议我如何devise一个NSURSessionNSURLConnection的系统,这将允许我使用完成处理程序为每个电话而不是代表?

PS我知道,我可以使用同步请求,但我真的想避免使用该选项

更新

有人build议添加.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) } 

而我所印的是“成功”。

好的,我终于明白了这一点(在@ cnoon的帮助下)。 返回的值是Resulttypes。 我找不到它的文档,但是源代码在这里可用。

为了检索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的响应的正确表示。