2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[Watch OS] 歩数を表示するだけの機能を実装してみる

Posted at

はじめに

Watch OSアプリでCoreMotionを使い歩数の値を取得・表示する実装をやってみました。
初めてのWatch OSアプリ開発なので基礎的なところからまとめました。

環境

Xcode 14.3

内容

プロジェクトの新規作成からやっていきます
まずはwatch OSのAppを選択

その後、Watch OS専用アプリかどうかを選択します。今回はWatch-only Appを選択

  • Watch-only App 
  • Watch App With New Companion iOS App

デフォルトはこんな形
スクリーンショット 2023-09-16 22.45.48.png

ContentViewに歩数を表示する最低実装をしてみる

import SwiftUI
import CoreMotion

struct ContentView: View {
    @State private var steps: Int = 0
    @State private var isUpdating: Bool = false
    private let pedometer = CMPedometer()

    var body: some View {
        VStack(spacing: 20) {
            Label(String(steps), systemImage: "figure.walk")
                .font(.title)

            Button(isUpdating ? "Stop Tracking" : "Start Tracking") {
                if isUpdating {
                    stopPedometerUpdates()
                } else {
                    startPedometerUpdates()
                }
                isUpdating.toggle()
            }
            .foregroundColor(isUpdating ? .red : .primary)
        }
        .padding()
    }

    private func startPedometerUpdates() {
        pedometer.startUpdates(from: Date()) { (data, error) in
            guard let data = data, error == nil else { return }

            Task { @MainActor in
                steps = Int(truncating: data.numberOfSteps)
            }
        }
    }

    private func stopPedometerUpdates() {
        pedometer.stopUpdates()
        steps = 0
    }
}

ここではimport CoreMotionしてからCMPedometerを使います
歩数計オブジェクト(CMPedometer)を使って、歩数や移動距離、昇降階数などの情報を取得することができます

UIはこんな感じに

この状態で動かしたらエラーがでました

This app has crashed because it attempted to access privacy-sensitive data without a usage description. The app's Info.plist must contain an NSMotionUsageDescription key with a string value explaining to the user how the app uses this data.

CoreMotionを使う上での許可をとってないよとのこと

こちらのNSMotionUsageDescriptionをInfo.plistに追加します

もう一度動かす

プライバシー許可の確認が表示され、シミュレーターでアプリも動くようになりました🎉

歩数の値は実機で動かさないと取得できませんが、後ほど動かしたところ上記の実装で問題なく動きました〜

おわりに

初めてのWatch OSアプリでしたがサクッと作れて驚きでした。
iOS17より追加されるHigh Frequency Motion APIなどはとても気になっているので少しずつWatch OSでできることを調べていこうと思います!

参考

2
1
1

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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?