Google Place Picker for iOSを使う時にいくつかハマりポイントがあったのでメモ。
Google Place Pickerってなんぞや?
https://developers.google.com/places/ios-api/placepicker?hl=ja
カレンダーアプリとかで場所を設定したい時に重宝するUIツールです。
基本的には↑のURLにあるサンプルコードを使いたいクラス内にコピペすれば動くはず…なのですがそうではなかったので注意しましょうという話です。
前提
マップ表示にあたって現在位置が必要なのでInfo.plistのPrivacy - Location When In Use Usage DescriptionやPrivacy - Location Always and When In Use Usage Descriptionを埋めないと当然ながら使えません。
CocoapodsのPodfileに
pod 'GooglePlaces'
pod 'GooglePlacePicker'
pod 'GoogleMaps'
を追記してpod installするのも忘れないようにしましょう。
Google Place APIとGoogle Map API両方を有効化する
Google Place APIの一部なんだから・・・と思いきやお使いのAPIキーでGoogle Map APIも有効化しないとGoogle Mapが表示されない模様です。
import GooglePlacePickerしよう
サンプルコードには書いてませんが冒頭でimport GooglePlacePickerしないとXcodeは認識しません。
delegateを指定しよう
https://developers.google.com/places/ios-api/placepicker?hl=ja にあるサンプルコードのアタマには
@IBAction func pickPlace(_ sender: UIButton) {
let config = GMSPlacePickerConfig(viewport: nil)
let placePicker = GMSPlacePickerViewController(config: config)
present(placePicker, animated: true, completion: nil)
}
と書いてありますがdelegateが指定されてないのでコレでは動きません。func placePicker(_ viewController: GMSPlacePickerViewController, didPick place: GMSPlace)を同じクラスに実装するのであれば
@IBAction func pickPlace(_ sender: UIButton) {
let config = GMSPlacePickerConfig(viewport: nil)
let placePicker = GMSPlacePickerViewController(config: config)
placePicker.delegate = self
present(placePicker, animated: true, completion: nil)
}
4行目。ちゃんとdelegateを指定しましょうね。
おわりに
Place Pickerとても便利ですがどうしてAuto Completeが別で存在しているのか謎(ただの下位互換にしか見えない)