あたも技術ブログ

セットジャパンコーポレーションの社員が運営しています。

【Swift】watchOS 3 × Core Motion

【Swift】watchOS 3 × Core Motion

今回はApple Watch Series 2を購入しましたので早速遊んでみました。

WatchAppのつくりかた

watchAppは基本的にiOS向けアプリの拡張機能なので、Extensionで実装します。

Target->「+」->watchOS->Watch Kit Appと進んでいけばExtensionを追加できます。

ターゲットの追加が完了すると、ソースツリー内に「ターゲット名」、「ターゲット名 Extension」のフォルダが2つ作成されます。

今回触るのは「ターゲット名 Extension」内のInterfaceController.swiftです。

InterfaceControllerの編集

import CoreMotion

class InterfaceController: WKInterfaceController {
    let motionMng = CMMotionManager()
    let queue = OperationQueue()
    
    override func awake(withContext context: Any?) {
        super.awake(withContext: context)
        
        // モーションが取得できない
        if ! motionMng.isDeviceMotionAvailable {
            return
        }
        
        // 値の取得を開始
        motionMng.startDeviceMotionUpdates(to: queue) {
            deviceMotion, error in
            // エラー
            if error != nil {
                print("error: \(error!)")
            }
            // 値の取得に成功
            if deviceMotion != nil {
                print("姿勢角 = \(deviceMotion!.attitude)")
                print("重力加速度 = \(deviceMotion!.gravity)")
                print("回転率 = \(deviceMotion!.rotationRate)")
                print("デバイスの加速度 = \(deviceMotion!.userAcceleration)")
                print("-------------------------------------------")
            }
        }
    }


}

まとめ

今回は値の取得のみでしたが、この値を計算し、水平器やなど作れたら良いかなー 走ってるときと車移動などの判別はデバイスの加速度などを見て判断できるのではないでしょうか