正如其他人所指出的那樣,沒有一個預定義的方法做搜索,但您可以使用網絡請求訪問Google Geocoding API自己:
func performGoogleSearch(for string: String) {
strings = nil
tableView.reloadData()
var components = URLComponents(string: "https://maps.googleapis.com/maps/api/geocode/json")!
let key = URLQueryItem(name: "key", value: "...") // use your key
let address = URLQueryItem(name: "address", value: string)
components.queryItems = [key, address]
let task = URLSession.shared.dataTask(with: components.url!) { data, response, error in
guard let data = data, let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200, error == nil else {
print(String(describing: response))
print(String(describing: error))
return
}
guard let json = try! JSONSerialization.jsonObject(with: data) as? [String: Any] else {
print("not JSON format expected")
print(String(data: data, encoding: .utf8) ?? "Not string?!?")
return
}
guard let results = json["results"] as? [[String: Any]],
let status = json["status"] as? String,
status == "OK" else {
print("no results")
print(String(describing: json))
return
}
DispatchQueue.main.async {
// now do something with the results, e.g. grab `formatted_address`:
let strings = results.flatMap { $0["formatted_address"] as? String }
...
}
}
task.resume()
}
來源
2017-07-03 17:31:30
Rob