gpt4 book ai didi

ios - swift 2.0 : Reading HealthKit HeartRate Data - unexpectedly found nil while unwrapping an Optional

转载 作者:搜寻专家 更新时间:2023-10-31 23:01:52 24 4
gpt4 key购买 nike

我正在尝试对 HealthKit 中的心率数据进行统计查询。

下面的代码可以编译,但在函数调用时会导致以下错误:

fatal error: unexpectedly found nil while unwrapping an Optional value

错误发生在这一行:

让数量:HKQuantity = result!.averageQuantity()!;

为什么结果返回零?我已经验证 HealthKit 中提供了 Heart Rate 数据,所以我不相信这是因为查询中的数据不存在。

有什么想法吗?有一个更好的方法吗?

代码如下:

func readHeartRate() {
let sampleType = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)!
let nowDate = NSDate()
let calendar = NSCalendar.autoupdatingCurrentCalendar()

let yearMonthDay: NSCalendarUnit = [NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day]

let components: NSDateComponents = calendar.components(yearMonthDay , fromDate: nowDate)
let beginOfDay : NSDate = calendar.dateFromComponents(components)!
let predicate : NSPredicate = HKQuery.predicateForSamplesWithStartDate(beginOfDay, endDate: nowDate, options: HKQueryOptions.StrictStartDate)

let squery = HKStatisticsQuery(quantityType: sampleType, quantitySamplePredicate: predicate, options: HKStatisticsOptions.None, completionHandler: { (squery, result, error) -> Void in

dispatch_async( dispatch_get_main_queue(), { () -> Void in

let quantity : HKQuantity = result!.averageQuantity()!;
let beats : Double = quantity.doubleValueForUnit(self.heartRateUnit)
print(beats)
})
})

healthKitStore.executeQuery(squery)
}

最佳答案

result 参数不保证为非零。如果结果不是 nil,你应该只解包并使用它,否则检查 error 看看哪里出了问题。您可能会发生许多您无法控制的错误(例如,设备可能在处理您的查询时被锁定,或者执行查询的系统守护程序可能崩溃)。

关于ios - swift 2.0 : Reading HealthKit HeartRate Data - unexpectedly found nil while unwrapping an Optional,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32684329/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com