MST

星途 面试题库

面试题:Swift实现健康与健身数据的实时监测及处理

使用Swift结合HealthKit框架,阐述如何实现对用户心率数据的实时监测。当监测到心率异常(假设高于120或低于60为异常)时,如何在应用中弹出提示框告知用户,并记录异常时间。请给出完整的代码逻辑和关键步骤。
24.7万 热度难度
编程语言Swift

知识考点

AI 面试

面试题答案

一键面试

关键步骤

  1. 配置项目并导入HealthKit框架:在Xcode项目中导入HealthKit框架,并在Info.plist文件中添加健康数据访问权限描述。
  2. 请求授权:在应用启动时,请求用户授权访问心率数据。
  3. 创建查询:使用HKQuery来实时获取心率数据。
  4. 监测心率并判断异常:在获取到心率数据后,判断是否异常。
  5. 弹出提示框并记录异常时间:如果心率异常,弹出提示框并记录异常时间。

完整代码逻辑

import HealthKit
import UIKit

class HeartRateMonitor {
    let healthStore = HKHealthStore()
    var heartRateQuery: HKQuery?

    func requestAuthorization() {
        guard HKHealthStore.isHealthDataAvailable() else {
            print("Health data is not available on this device.")
            return
        }

        let heartRateType = HKObjectType.quantityType(forIdentifier:.heartRate)!
        healthStore.requestAuthorization(toShare: nil, read: [heartRateType]) { (success, error) in
            if let error = error {
                print("Authorization error: \(error)")
            } else if success {
                print("Authorization successful.")
            }
        }
    }

    func startMonitoring() {
        let heartRateType = HKObjectType.quantityType(forIdentifier:.heartRate)!
        let predicate = HKQuery.predicateForSamples(withStart: Date.distantPast, end: Date(), options:.strictEndDate)

        let updateHandler: (HKAnchoredObjectQuery, [HKSample]?, [HKDeletedObject]?, HKQueryAnchor?, Error?) -> Void = { (query, samples, deletedObjects, anchor, error) in
            guard let samples = samples as? [HKQuantitySample] else { return }
            for sample in samples {
                let heartRate = sample.quantity.doubleValue(for: HKUnit.count().unitDivided(by: HKUnit.minute()))
                self.checkHeartRate(heartRate)
            }
        }

        heartRateQuery = HKAnchoredObjectQuery(type: heartRateType, predicate: predicate, anchor: nil, limit: HKObjectQueryNoLimit, resultsHandler: updateHandler)
        heartRateQuery?.updateHandler = updateHandler

        if let query = heartRateQuery {
            healthStore.execute(query)
        }
    }

    func checkHeartRate(_ heartRate: Double) {
        if heartRate > 120 || heartRate < 60 {
            let alertController = UIAlertController(title: "心率异常", message: "当前心率为 \(heartRate),已超出正常范围。", preferredStyle:.alert)
            let okAction = UIAlertAction(title: "确定", style:.default, handler: nil)
            alertController.addAction(okAction)

            // 获取当前视图控制器以显示提示框
            guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
                  let rootViewController = windowScene.windows.first?.rootViewController else { return }
            rootViewController.present(alertController, animated: true, completion: nil)

            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
            let currentDate = Date()
            let dateString = dateFormatter.string(from: currentDate)
            print("心率异常时间: \(dateString)")
        }
    }
}

AppDelegate.swift中可以这样调用:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    let monitor = HeartRateMonitor()
    monitor.requestAuthorization()
    monitor.startMonitoring()
    return true
}