LoginSignup
1
2

More than 5 years have passed since last update.

WatchKitを試してみる2 位置情報の読み取り

Posted at

開発環境

  • 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。
うーん、あんまり単体で出来る事ないのね

参考ページ

A watchOS 2 WatchKit Map Tutorial

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2