面试题答案
一键面试关键步骤
- 配置项目并导入HealthKit框架:在Xcode项目中导入HealthKit框架,并在
Info.plist
文件中添加健康数据访问权限描述。 - 请求授权:在应用启动时,请求用户授权访问心率数据。
- 创建查询:使用
HKQuery
来实时获取心率数据。 - 监测心率并判断异常:在获取到心率数据后,判断是否异常。
- 弹出提示框并记录异常时间:如果心率异常,弹出提示框并记录异常时间。
完整代码逻辑
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
}