【watchOS】Apple Watchで位置情報取得
Apple Watch seriese2から単体で位置情報を取得できるようになりました。
ということで、今回はApple Watchで位置情報を取得してみました。
コード
まずはコードをサクッと書いてみましょう プロジェクトを作成し、ターゲットを追加、WatchKit Appを選択しましょう。
そして追加されたInterfaceController.swift
を編集します。
import WatchKit import Foundation import CoreLocation class InterfaceController: WKInterfaceController, CLLocationManagerDelegate { @IBOutlet var latitudeLabel: WKInterfaceLabel! // InterfaceBuiderから追加 @IBOutlet var longitudeLabel: WKInterfaceLabel! // InterfaceBuiderから追加 private var locationManager: CLLocationManager = CLLocationManager() private var currentLocation: CLLocation! override func willActivate() { super.willActivate() locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.distanceFilter = 1000 locationManager.delegate = self let status = CLLocationManager.authorizationStatus() if(status == CLAuthorizationStatus.notDetermined) { self.locationManager.requestWhenInUseAuthorization() } self.locationManager.startUpdatingLocation() } override func didDeactivate() { super.didDeactivate() } // MARK: - CLLocationManagerDelegate func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations:[CLLocation]) { let locationData = locations.last as CLLocation! self.currentLocation = locationData latitudeLabel.setText(String(self.currentLocation.coordinate.latitude)) longitudeLabel.setText(String(self.currentLocation.coordinate.longitude)) self.locationManager.stopUpdatingLocation() } private func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status:CLAuthorizationStatus) { if (status == .notDetermined) { if (self.locationManager.responds(to: #selector(CLLocationManager.requestWhenInUseAuthorization))) { self.locationManager.requestWhenInUseAuthorization() } } } }
確認
AppleWatcとペアリングしているiPhoneを機内モードにし、AppleWatc単体で位置情報を取得できるか確認します。
iPhoneとの接続時と比べ、若干精度が落ちるようですが、無事に位置情報の取得が確認できました。
MapViewを追加すればWatch内でMapの表示もできるようです。