Alamofire与谷歌地理编码api

时间:2015-08-21 15:24:44

标签: ios google-maps-api-3 google-api swift2 alamofire

在我的一个应用程序中,我需要对地址字符串进行地理编码。起初我考虑使用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来提取每个地方的时区。

使用NSURLConnectionNSURLSession执行此操作在我看来有点困难,因为我需要跟踪哪个会话/连接返回。所以,我想有一些使用完成处理程序的解决方案。

我尝试过使用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"。我希望我做错了,它可以修复,因为我真的希望能够使用闭包而不是委托调用。

我的问题是:

  1. 是否可以将Alamofire与Google地理编码API一起使用?
  2. 如果是的话,请告诉我我做错了什么?
  3. 如果不可能,请您建议我如何设计一个NSURSessionNSURLConnection s的系统,这样我就可以为每次通话而不是代表使用完成处理程序?
  4. 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"。

1 个答案:

答案 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响应的正确表示。