【Xcode/SwiftUI】CoreMotionで気圧を測る

実機テスト推奨です。

実装

Altimator.swift

import CoreMotion

final class Altimator {
    var altimeter: CMAltimeter?

    init() {
        altimeter = CMAltimeter()
    }

    func startUpdate(completion: @escaping (Double) -> Void) {
        guard let altimeter = altimeter else {
            return
        }

        if CMAltimeter.isRelativeAltitudeAvailable() {
            altimeter.startRelativeAltitudeUpdates(to: OperationQueue.main) { data, error in
                if error == nil {
                    guard let pressure = data?.pressure.doubleValue else {
                        return
                    }
                    print("気圧", pressure * 10)
                    completion(pressure * 10)
                } else {
                    // Handle error here
                }
            }
        }
    }

    func stopUpdate() {
        altimeter?.stopRelativeAltitudeUpdates()
    }
}

HomeView.swift (メインのView)

import SwiftUI
import CoreMotion

struct HomeView: View {
    private let altimator = Altimator()
    @State var pressureValue = 0.0

    var body: some View {
        VStack {
            Text(String(format: "%.2f", pressureValue))
                .font(.largeTitle)
            Text("hPa")
                .font(.title)
                .fontWeight(.semibold)
            startButton
            stopButton
        }
    }

    private var startButton: some View {
        Button {
            altimator.startUpdate { value in
                self.pressureValue = value
            }
        } label: {
            Text("測定開始")
        }
        .font(.custom(FontFamily.Caprasimo.regular, size: 24))
        .frame(width: UIScreen.main.bounds.width / 1.3, height: UIScreen.main.bounds.height / 28, alignment: .center)
        .padding()
        .foregroundColor(.white)
        .background(.orange)
        .padding()
    }

    private var stopButton: some View {
        Button {
            altimator.stopUpdate()
        } label: {
            Text("測定終了")
        }
        .font(.custom(FontFamily.Caprasimo.regular, size: 24))
        .frame(width: UIScreen.main.bounds.width / 1.3, height: UIScreen.main.bounds.height / 28, alignment: .center)
        .padding()
        .foregroundColor(.white)
        .background(.gray)
        .padding()
    }
}