在使用Google Places API时,如何根据用户输入的英国邮政编码来获取预测地址列表?我将GMSAutocompleteFilter
设置为键入.address
。我究竟做错了什么?屏幕截图已附上。完整的邮政编码为ig11 7ps
import UIKit
import GooglePlaces
class TestViewController: UIViewController {
var textField: UITextField?
var resultText: UITextView?
var fetcher: GMSAutocompleteFetcher?
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
edgesForExtendedLayout = []
// Set bounds in United Kingdom to
// - Easternmost point – Lowestoft Ness, Suffolk at 52°29′N 1°46′E
// - Westernmost point – Corrachadh Mòr, Highland at 56°42′N 6°13′W
let neBoundsCorner = CLLocationCoordinate2D(latitude: 52.48333333,
longitude: 1.76666667)
let swBoundsCorner = CLLocationCoordinate2D(latitude: 52.70000000,
longitude: 6.21666667)
let bounds = GMSCoordinateBounds(coordinate: neBoundsCorner,
coordinate: swBoundsCorner)
// Set up the autocomplete filter.
let filter = GMSAutocompleteFilter()
filter.type = .address
// Create the fetcher.
fetcher = GMSAutocompleteFetcher(bounds: bounds, filter: filter)
fetcher?.delegate = self
textField = UITextField(frame: CGRect(x: 5.0, y: 10.0,
width: view.bounds.size.width - 5.0,
height: 44.0))
textField?.autoresizingMask = .flexibleWidth
textField?.addTarget(self, action: #selector(textFieldDidChange(textField:)),
for: .editingChanged)
resultText = UITextView(frame: CGRect(x: 0, y: 45.0,
width: view.bounds.size.width,
height: view.bounds.size.height - 45.0))
resultText?.backgroundColor = UIColor(white: 0.95, alpha: 1.0)
resultText?.text = "No Results"
resultText?.isEditable = false
view.addSubview(textField!)
view.addSubview(resultText!)
}//end viewDidLoad
func textFieldDidChange(textField: UITextField) {
fetcher?.sourceTextHasChanged(textField.text!)
}
}//end of class
extension TestViewController: GMSAutocompleteFetcherDelegate {
func didAutocomplete(with predictions: [GMSAutocompletePrediction]) {
let resultsStr = NSMutableString()
for prediction in predictions {
resultsStr.appendFormat("%@\n", prediction.attributedPrimaryText.string)
}
resultText?.text = resultsStr as String
}
func didFailAutocompleteWithError(_ error: Error) {
resultText?.text = error.localizedDescription
}
}