google places autocomplete ios swift integrate with uitextfield

8.6k Views Asked by At

I am trying to implement google places auto complete api in swift 2.0 project by using the following library:

https://github.com/watsonbox/ios_google_places_autocomplete

the only thing i am not able to figure out is that i want to integrate this with uitextfield present in my app form which has country and city fields.

I have implemented this app in a demo project and found out that it also provides me lat long of the location also.

Please help me out by guiding me to integrate this library with the uitextfield so when user types in uitextfield the results are shown below uitextfield only.

By working to implement code in demo app i came to know that the searchbox opens up with the following code:

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

I am not able to figure out how to get this viewcontroller functionality work on my uitextfield so it can work exactly as it works on uitextfield

2

There are 2 best solutions below

0
On

Why do not use Google Places API for iOS ? It has all the capability as seen on the mentioned library. Here is the link https://developers.google.com/places/ios-api/autocomplete

and you can use the fetcher object to get the predictions and according to whatever requirement you can customize the result. Hope this helps

5
On

Google autocomplete API using search bar

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: searchText)
}

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

    operationQueue.addOperation { () -> Void in
        self.forwardGeoCoding(searchTexts:searchText)
    }
}

//MARK: - Search place from Google -


func forwardGeoCoding(searchTexts:String) {
    googlePlacesResult(input: searchTexts) { (result) -> Void in
        let searchResult:NSDictionary = ["keyword":searchTexts,"results":result]
        if result.count > 0
        {
            let features = searchResult.value(forKey: "results") as! [AnyObject]
            self.arrPlaces = NSMutableArray(capacity: 100)

            for dictAddress in features   {
                if let content = dictAddress.value(forKey:"description") as? String {
                    self.arrPlaces.addObjects(from: [content])
                }
            }
            DispatchQueue.main.async {
                //self.tblOfflineCity.reloadData()
            }
        }
    }
}

func googlePlacesResult(input: String, completion: @escaping (_ result: NSArray) -> Void) {
    let searchWordProtection = input.replacingOccurrences(of: " ", with: "")
    if searchWordProtection.count != 0 {
        let urlString = NSString(format: googleAutoCompeteApi as NSString,input,currentLat,currentLong,googleServerkey)
        let url = NSURL(string: urlString.addingPercentEscapes(using: String.Encoding.utf8.rawValue)!)
        let defaultConfigObject = URLSessionConfiguration.default
        let delegateFreeSession = URLSession(configuration: defaultConfigObject, delegate: nil, delegateQueue: OperationQueue.main)
        let request = NSURLRequest(url: url! as URL)
        let task =  delegateFreeSession.dataTask(with: request as URLRequest,completionHandler: {
            (data, response, error) -> Void in
            if let data = data {
                do {
                    let jSONresult = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.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] as [NSObject : AnyObject] as? [String : Any])
                        let arr:NSArray = [newError]
                        completion(arr)
                        return
                    } else {
                        completion(results)
                    }
                }
                catch {
                    print("json error: \(error)")
                }
            } else if error != nil {
                // print(error.description)
            }
        })
        task.resume()
    }
}

you will get result in self.arrPlaces. To use in uitextField only you need to call function using uitextField delegate instead of searchbar