Google api auto-complete tutorial for quick

I would like to have an autocomplete text box that automatically fills in places for me as for an android:

https://developers.google.com/places/training/autocomplete-android

Does anyone know where I can find a tutorial for this or an example?

Thanks!

+6
source share
3 answers

Steps:

  • Add Alamofire CocoaPods to your fast project.
  • Locate the Google place API key in the Google API Console.
  • Add the following code

ViewController.swift

import UIKit class ViewController: UIViewController { override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) let gpaViewController = GooglePlacesAutocomplete( apiKey: "YOUR GOOGLE PLACE API KEY", placeType: .Address ) gpaViewController.placeDelegate = self presentViewController(gpaViewController, animated: true, completion: nil) } } extension ViewController: GooglePlacesAutocompleteDelegate { func placeSelected(place: Place) { println(place.description) } func placeViewClosed() { dismissViewControllerAnimated(true, completion: nil) } } 

GooglePlacesAutocomplete.swift

 import UIKit import Alamofire enum PlaceType: Printable { case All case Geocode case Address case Establishment case Regions case Cities var description : String { switch self { case .All: return "" case .Geocode: return "geocode" case .Address: return "address" case .Establishment: return "establishment" case .Regions: return "regions" case .Cities: return "cities" } } } struct Place { let id: String let description: String } protocol GooglePlacesAutocompleteDelegate { func placeSelected(place: Place) func placeViewClosed() } // MARK: - GooglePlacesAutocomplete class GooglePlacesAutocomplete: UINavigationController { var gpaViewController: GooglePlacesAutocompleteContainer? var placeDelegate: GooglePlacesAutocompleteDelegate? { get { return gpaViewController?.delegate } set { gpaViewController?.delegate = newValue } } convenience init(apiKey: String, placeType: PlaceType = .All) { let gpaViewController = GooglePlacesAutocompleteContainer( apiKey: apiKey, placeType: placeType ) self.init(rootViewController: gpaViewController) self.gpaViewController = gpaViewController let closeButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Stop, target: self, action: "close") gpaViewController.navigationItem.leftBarButtonItem = closeButton gpaViewController.navigationItem.title = "Enter Address" } func close() { placeDelegate?.placeViewClosed() } } // MARK: - GooglePlaceSearchDisplayController class GooglePlaceSearchDisplayController: UISearchDisplayController { override func setActive(visible: Bool, animated: Bool) { if active == visible { return } searchContentsController.navigationController?.navigationBarHidden = true super.setActive(visible, animated: animated) searchContentsController.navigationController?.navigationBarHidden = false if visible { searchBar.becomeFirstResponder() } else { searchBar.resignFirstResponder() } } } // MARK: - GooglePlacesAutocompleteContainer class GooglePlacesAutocompleteContainer: UIViewController { var delegate: GooglePlacesAutocompleteDelegate? var apiKey: String? var places = [Place]() var placeType: PlaceType = .All convenience init(apiKey: String, placeType: PlaceType = .All) { self.init(nibName: "GooglePlacesAutocomplete", bundle: nil) self.apiKey = apiKey self.placeType = placeType } override func viewDidLoad() { super.viewDidLoad() let tv: UITableView? = searchDisplayController?.searchResultsTableView tv?.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell") } } // MARK: - GooglePlacesAutocompleteContainer (UITableViewDataSource / UITableViewDelegate) extension GooglePlacesAutocompleteContainer: UITableViewDataSource, UITableViewDelegate { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return places.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = self.searchDisplayController?.searchResultsTableView?.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell // Get the corresponding candy from our candies array let place = self.places[indexPath.row] // Configure the cell cell.textLabel.text = place.description cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { delegate?.placeSelected(self.places[indexPath.row]) } } // MARK: - GooglePlacesAutocompleteContainer (UISearchDisplayDelegate) extension GooglePlacesAutocompleteContainer: UISearchDisplayDelegate { func searchDisplayController(controller: UISearchDisplayController, shouldReloadTableForSearchString searchString: String!) -> Bool { getPlaces(searchString) return false } private func getPlaces(searchString: String) { Alamofire.request(.GET, "https://maps.googleapis.com/maps/api/place/autocomplete/json", parameters: [ "input": searchString, "type": "(\(placeType.description))", "key": apiKey ?? "" ]).responseJSON { request, response, json, error in if let response = json as? NSDictionary { if let predictions = response["predictions"] as? Array<AnyObject> { self.places = predictions.map { (prediction: AnyObject) -> Place in return Place( id: prediction["id"] as String, description: prediction["description"] as String ) } } } self.searchDisplayController?.searchResultsTableView?.reloadData() } } } 

GooglePlacesAutocomplete.xib

GooglePlacesAutocomplete.xib

Hope this helps others.

+7
source
 //Using Alamofire get the autocomplete Google places result from data, //you can show it in table view cell //plist configuration //<key>NSAppTransportSecurity</key> // <dict> // <key>NSAllowsArbitraryLoads</key> // <true/> // </dict> import UIKit import Alamofire class GooglePlacesViewController: UIViewController,UISearchBarDelegate,UITableViewDataSource,UITableViewDelegate { @IBOutlet weak var srchLocation: UISearchBar! @IBOutlet weak var tblLoction: UITableView! var arrPlaces = NSMutableArray(capacity: 100) let operationQueue = OperationQueue() let currentLat = 51.5033640 let currentLong = -0.1276250 var LocationDataDelegate : LocationData! = nil var tblLocation : UITableView! var lblNodata = UILabel() override func viewDidLoad() { super.viewDidLoad() lblNodata.frame = CGRect(x: 0, y: 80, width: self.view.frame.size.width, height: self.view.frame.size.height-60) lblNodata.text = "Please enter text to get your location" self.view.addSubview(lblNodata) srchLocation.placeholder = "Ente your location details" lblNodata.textAlignment = .center } func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { self.beginSearching(searchText: searchText) } func beginSearching(searchText:String) { if searchText.characters.count == 0 { self.arrPlaces.removeAllObjects() tblLoction.isHidden = true lblNodata.isHidden = false return } operationQueue.addOperation { () -> Void in self.forwardGeoCoding(searchText: searchText) } } //MARK: - Search place from Google - func forwardGeoCoding(searchText:String) { googlePlacesResult(input: searchText) { (result) -> Void in let searchResult:NSDictionary = ["keyword":searchText,"results":result] if result.count > 0 { let features = searchResult.value(forKey: "results") as! NSArray self.arrPlaces = NSMutableArray(capacity: 100) print(features.count) for jk in 0...features.count-1 { let dict = features.object(at: jk) as! NSDictionary self.arrPlaces.add(dict) } DispatchQueue.main.async(execute: { if self.arrPlaces.count != 0 { self.tblLoction.isHidden = false self.lblNodata.isHidden = true self.tblLoction.reloadData() } else { self.tblLoction.isHidden = true self.lblNodata.isHidden = false self.tblLoction.reloadData() } }); } } } //MARK: - Google place API request - func googlePlacesResult(input: String, completion: @escaping (_ result: NSArray) -> Void) { let searchWordProtection = input.replacingOccurrences(of: " ", with: ""); if searchWordProtection.characters.count != 0 { let urlString = NSString(format: "https://maps.googleapis.com/maps/api/place/autocomplete/json?input=%@&types=establishment|geocode&location=%@,%@&radius=500&language=en&key= your key",input,"\(currentLocationLatitude)","\(currentLocationLongtitude)") print(urlString) let url = NSURL(string: urlString.addingPercentEscapes(using: String.Encoding.utf8.rawValue)!) print(url!) 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]) let arr:NSArray = [newError] completion(arr) return } else { completion(results) } } catch { print("json error: \(error)") } } else if let error = error { print(error) } }) task.resume() } } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return arrPlaces.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let tblCell = tableView.dequeueReusableCell(withIdentifier: "locationCell") let dict = arrPlaces.object(at: indexPath.row) as! NSDictionary tblCell?.textLabel?.text = dict.value(forKey: "description") as? String tblCell?.textLabel?.numberOfLines = 0 tblCell?.textLabel?.sizeToFit() return tblCell! } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if LocationDataDelegate != nil { let dict = arrPlaces.object(at: indexPath.row) as! NSDictionary print(dict.value(forKey: "terms") as! NSArray) let ArrSelected = dict.value(forKey: "terms") as! NSArray LocationDataDelegate.didSelectLocationData(LocationData: ArrSelected) } self.dismiss(animated: true, completion: nil) } } 
+1
source

Source: https://habr.com/ru/post/982095/


All Articles