検索バーを使用した Google オートコンプリート API
1)
let googleAutoCompeteApi = "https://maps.googleapis.com/maps/api/place/autocomplete/json?input=%@&types=establishment|geocode&location=%@,%@&radius=500&language=en&key=%@"
var arrPlaces = NSMutableArray(capacity: 100)
let operationQueue = NSOperationQueue()
let googleServerkey = "Your API KEY"
2)
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
self.beginSearching(searchText: searchText)
}
func beginSearching(searchText:String) {
if searchText.count == 0 {
self.arrPlaces.removeAllObjects()
// self.tblOfflineCity.reloadData()
return
}
operationQueue.addOperation { () -> Void in
self.forwardGeoCoding(searchTexts:searchText)
}
}
//MARK: - Search place from Google -
func forwardGeoCoding(searchTexts:String) {
googlePlacesResult(input: searchTexts) { (result) -> Void in
let searchResult:NSDictionary = ["keyword":searchTexts,"results":result]
if result.count > 0
{
let features = searchResult.value(forKey: "results") as! [AnyObject]
self.arrPlaces = NSMutableArray(capacity: 100)
for dictAddress in features {
if let content = dictAddress.value(forKey:"description") as? String {
self.arrPlaces.addObjects(from: [content])
}
}
DispatchQueue.main.async {
//self.tblOfflineCity.reloadData()
}
}
}
}
func googlePlacesResult(input: String, completion: @escaping (_ result: NSArray) -> Void) {
let searchWordProtection = input.replacingOccurrences(of: " ", with: "")
if searchWordProtection.count != 0 {
let urlString = NSString(format: googleAutoCompeteApi as NSString,input,currentLat,currentLong,googleServerkey)
let url = NSURL(string: urlString.addingPercentEscapes(using: String.Encoding.utf8.rawValue)!)
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] as [NSObject : AnyObject] as? [String : Any])
let arr:NSArray = [newError]
completion(arr)
return
} else {
completion(results)
}
}
catch {
print("json error: \(error)")
}
} else if error != nil {
// print(error.description)
}
})
task.resume()
}
}
self.arrPlaces で結果が得られます。uitextField でのみ使用するには、検索バーの代わりに uitextField デリゲートを使用して関数を呼び出す必要があります