CoreLocationで位置情報と方角を取得する
CoreLocationで位置情報を取得する方法を紹介します。
①CoreLocation.frameworkを追加
「General>Linked Frameworks and Libraries」にCoreLocation.frameworkを追加しimportします。
import CoreLocation
②info.plistにKeyを設定
info.plistでPrivacy - Location When In Use Usage Descriptionを設定します。Valueは空でも大丈夫です。
③LocationManagerを作成
ロケーションマネージャーを作成し、delegateをselfに設定します。CLLocationManagerDelegateを継承するのを忘れずに。
myLocationManager = CLLocationManager() myLocationManager.delegate = self
認証ステータスをチェックしてnotDeterminedの場合認証ウィンドウを表示させます。
let status = CLLocationManager.authorizationStatus() if(status == CLAuthorizationStatus.notDetermined){ self.myLocationManager.requestWhenInUseAuthorization() }
方角を取得する場合はstartUpdatingHeading、位置を取得する場合はstartUpdatingLocationを実行
myLocationManager.startUpdatingHeading() //方角アップデート myLocationManager.startUpdatingLocation() //位置アップデート
④方角を取得する
func locationManager(_ manager:CLLocationManager,didUpdateHeading newHeading:CLHeading){ print("方角:".appendingFormat("%.2f",newHeading.magneticHeading)) }
⑤位置を取得する
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { guard let newLocation = locations.first else { return } print("緯度:".appendingFormat("%.2f",newLocation.coordinate.latitude)) print("緯度:".appendingFormat("%.2f",newLocation.coordinate.longitude)) }
plistは忘れがちなので注意してください。