我正在尝试在HealthKit中对心率数据进行统计查询。
下面的代码编译,但在函数调用时会导致以下错误:
致命错误:在展开可选值时意外找到零
此错误发生在这一行:
let quantity : HKQuantity = result!.averageQuantity()!;
为什么结果是零?我已经验证了心率数据在HealthKit中是可用的,所以我不认为这是因为查询中的数据不存在。
有什么想法吗?有更好的方法吗?
代码如下:
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)
}发布于 2015-09-24 21:06:11
最后,我在这里采取了一种不同的方法,通过查询一组心率数据并取平均值来解决这个问题。
注意: getDayofWeek函数只接受一个NSDate,并返回一周中的一个字符串。
func readHRbyDate(latestXSamples: Int, startDate: NSDate, endDate: NSDate, completion: (((String, CGFloat), NSError!) -> Void)!)
{
let sampleType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)
let predicate = HKQuery.predicateForSamplesWithStartDate(startDate, endDate: endDate, options: HKQueryOptions.None)
let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: true)
var HRdata:(String,CGFloat) = ("N/A",0)
var bpm: Int = 0
var totalBPMforDay = [Int]()
var BPMCount: Int = 0
var sumBPM: Int = 0
let query = HKSampleQuery(sampleType: sampleType!, predicate: predicate, limit: latestXSamples, sortDescriptors: [sortDescriptor])
{ (query, results, error) in
if let queryError = error {
print("Problem fetching HR data")
completion(("nil",0.0),queryError)
return
}else{
for result in results! {
bpm = Int(((result.valueForKeyPath("_quantity._value"))?.floatValue)! * 60.0)
totalBPMforDay += [Int(((result.valueForKeyPath("_quantity._value"))?.floatValue)! * 60.0)]
BPMCount = Int(totalBPMforDay.count)
sumBPM += Int(((result.valueForKeyPath("_quantity._value"))?.floatValue)! * 60.0)
let HRAvg = sumBPM / BPMCount
HRdata = (self.getDayOfWeek(result.startDate),CGFloat(HRAvg))
}
if completion != nil {
completion(HRdata,nil)
}
}
}
healthKitStore.executeQuery(query)
}发布于 2015-09-21 20:29:03
result参数不能保证为非零。只有在结果不是零的情况下,才应该展开和使用结果,否则应该检查error,看看出了什么问题。可能会发生一些您无法控制的错误(例如,在处理查询时设备可能被锁定,或者执行查询的系统守护进程可能崩溃)。
https://stackoverflow.com/questions/32684329
复制相似问题