開発環境
- XCode10.1
- Swift4.2.1
前回から時間が空きましたがWatchKitを試してみる第2回です。
今回はAppleWatch本体のGPS情報を読み取る試み。
といっても一旦、理解すれば簡単なもの。
InterfaceController.swift
import CoreLocation
class InterfaceController: WKInterfaceController, CLLocationManagerDelegate {
var locationManager = CLLocationManager()
override func awake(withContext context: Any?) {
super.awake(withContext: context)
locationManager.delegate = self
locationManager.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let lat = locations.last?.coordinate.latitude
let long = locations.last?.coordinate.longitude
print("lat: " + (lat?.description)! + "long: " + (long?.description)!)
}
ViewController.swift
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
var locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
locationManager.requestAlwaysAuthorization()
}
}
GPSを使う許可はiPhoneのアプリ側にCLLocationManagerの許可をとる記述が必要みたいです。
後はiPhone側のinfo.plistに下記の3つの記述を追加。
Privacy - Location Always and When In Use Usage Description
Privacy - Location Always Usage Description
Privacy - Location When In Use Usage Description
後は最初にiPhone側のアプリを立ち上げて許可を取ればOK。
うーん、あんまり単体で出来る事ないのね