谷歌地方自动完成ios swift与uitextfield集成

时间:2016-01-23 14:39:03

标签: ios swift2 google-places-api xcode7.1

我正在尝试使用以下库在swift 2.0项目中实现google places auto complete api:

https://github.com/watsonbox/ios_google_places_autocomplete

我唯一无法弄清楚的是,我想将其与我的应用表单中包含国家和城市字段的uitextfield进行整合。

我已经在一个演示项目中实现了这个应用程序,并发现它也为我提供了很长的位置。

请指导我将此库与uitextfield集成,以帮助我。因此,当用户在uitextfield中输入结果时,结果仅显示在uitextfield下方。

通过努力在演示应用程序中实现代码,我开始知道搜索框打开时带有以下代码:

let gpaViewController = GooglePlacesAutocomplete(
        apiKey: "API KEY FROM GOOGLE PLACES API",
        placeType: .Address
    )

我无法弄清楚如何让这个viewcontroller功能在我的uitextfield上运行,因此它可以在uitextfield上完全正常工作

2 个答案:

答案 0 :(得分:3)

为什么不在iOS上使用Google Places API?它具有上述库中所见的所有功能。这是链接https://developers.google.com/places/ios-api/autocomplete

并且您可以使用fetcher对象来获取预测,并根据您可以自定义结果的任何要求。希望这有帮助

答案 1 :(得分:1)

使用搜索栏的Google自动填充API

1)

let googleAutoCompeteApi = "https://maps.googleapis.com/maps/api/place/autocomplete/json?input=%@&types=establishment|geocode&location=%@,%@&radius=500&language=en&key=%@"
var arrPlaces = NSMutableArray(capacity: 100)
let operationQueue = NSOperationQueue()
let googleServerkey = "Your API KEY"

<强> 2)

func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
        self.beginSearching(searchText)
    }

    func beginSearching(searchText:String) {
        if searchText.characters.count == 0 {
            self.arrPlaces.removeAllObjects()
            self.tblOfflineCity.reloadData()
            return
        }

        operationQueue.addOperationWithBlock { () -> Void in
            self.forwardGeoCoding(searchText)
        }
    }

    //MARK: - Search place from Google -
    func forwardGeoCoding(searchText:String) {
        googlePlacesResult(searchText) { (result) -> Void in
            let searchResult:NSDictionary = ["keyword":searchText,"results":result]
            if result.count > 0
            {
                let features = searchResult.valueForKey("results") as! [AnyObject]
                self.arrPlaces = NSMutableArray(capacity: 100)
                for dictAddress in features   {
                    self.arrPlaces.addObject(dictAddress.valueForKey("description")!)
                }
                dispatch_async(dispatch_get_main_queue(), {
                    self.tblOfflineCity.reloadData()
                });
            }
        }
    }

    //MARK: - Google place API request -
    func googlePlacesResult(input: String, completion: (result: NSArray) -> Void) {
        let searchWordProtection = input.stringByReplacingOccurrencesOfString(" ", withString: "")
        if searchWordProtection.characters.count != 0 {
            let urlString = NSString(format: googleAutoCompeteApi,input,currentLat,currentLong,googleServerkey)
            let url = NSURL(string: urlString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)
            let defaultConfigObject = NSURLSessionConfiguration.defaultSessionConfiguration()
            let delegateFreeSession = NSURLSession(configuration: defaultConfigObject, delegate: nil, delegateQueue: NSOperationQueue.mainQueue())
            let request = NSURLRequest(URL: url!)
            let task =  delegateFreeSession.dataTaskWithRequest(request,
                                                                completionHandler: {
                                                                    (data, response, error) -> Void in
                                                                    if let data = data {

                                                                        do {
                                                                            let jSONresult = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as! [String:AnyObject]
                                                                            let results:NSArray = jSONresult["predictions"] as! NSArray
                                                                            let status = jSONresult["status"] as! String

                                                                            if status == "NOT_FOUND" || status == "REQUEST_DENIED" {

                                                                                let userInfo:NSDictionary = ["error": jSONresult["status"]!]
                                                                                let newError = NSError(domain: "API Error", code: 666, userInfo: userInfo as [NSObject : AnyObject])
                                                                                let arr:NSArray = [newError]
                                                                                completion(result: arr)
                                                                                return
                                                                            } else {
                                                                                completion(result: results)
                                                                            }
                                                                        }
                                                                        catch {
                                                                            print("json error: \(error)")
                                                                        }
                                                                    } else if let error = error {
                                                                        print(error.description)
                                                                    }
            })
            task.resume()
        }
    }

你会得到self.arrPlaces的结果。要仅在uitextField中使用,您需要使用uitextField委托而不是搜索栏来调用函数