Romit Kumar
Romit Kumar

Reputation: 3300

Can we use Google's place autocomplete api to populate out tableview cells on swift?

I want to know the process of how we can use google place api so that when we enter a text in a UITextField, the tableview get reloaded to show the autocomplete results. The Documentation given on Google uses its own API. Im new to ios development. Can anyone help me how to proceed? So far i'm done with pod setup etc and i'm able to get text text enter by user in textfield's delegate method.

This is my code, im unable to see any result in my tableview

import UIKit
import GooglePlaces

class ViewController: UIViewController {
  @IBOutlet weak var schoolTextField: UITextField!
  @IBOutlet weak var schooltableView: UITableView!

  var placesClient : GMSPlacesClient?
  var resultArray  = [String]()

  override func viewDidLoad() {
    super.viewDidLoad()
  }

  func placeAutocomplete(text:String) {
    let filter = GMSAutocompleteFilter()
    filter.type = .noFilter
    placesClient?.autocompleteQuery(text, bounds: nil, filter: filter, callback: {(results, error) -> Void in   //unable to enter in this block
    if let error = error {
      print("Autocomplete error \(error)")
      return
    }
    if let results = results {
     self.resultArray = [String]()
     for result in results {
      self.resultArray.append(String(describing: result.attributedFullText)) 
      print("Result \(result.attributedFullText) with placeID \(result.placeID)")
    }
  }
  self.schooltableView.reloadData()
  })
 }
}

extension ViewController:UITextFieldDelegate {
  func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let currentText = textField.text ?? ""
    placeAutocomplete(text:currentText)
    return true
     }
   }

  extension ViewController:UITableViewDelegate,UITableViewDataSource {
  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return resultArray.count
  }

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)as! SchoolCell
    cell.schoolLabel.text = resultArray[indexPath.row]
    return cell
  }

  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    //do something, unable to reach here
  }
}

Upvotes: 3

Views: 948

Answers (1)

Leo Valentim
Leo Valentim

Reputation: 461

You forgot to instantiate GMSPlacesClient and to call delegate to UITextField and UITableView in viewDidLoad.

override func viewDidLoad() {
    super.viewDidLoad()

    self.placesClient = GMSPlacesClient()
    self.schoolTextField.delegate = self
    self.schooltableView.delegate = self
    self.schooltableView.dataSource = self
}

Upvotes: 2

Related Questions