我想了解我们如何使用google place api的过程,这样当我们在UITextField中输入文本时,会重新加载tableview以显示自动完成结果。 Google上提供的文档使用自己的API。我是ios开发的新手。任何人都可以帮我怎么办?到目前为止,我已经完成了pod设置等,我可以在textfield的委托方法中输入用户输入的文本文本。
这是我的代码,我无法在我的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
}
}
答案 0 :(得分:2)
您忘记实例化GMSPlacesClient并在viewDidLoad中调用委托给UITextField和UITableView。
override func viewDidLoad() {
super.viewDidLoad()
self.placesClient = GMSPlacesClient()
self.schoolTextField.delegate = self
self.schooltableView.delegate = self
self.schooltableView.dataSource = self
}