我正在HealthKit中尝试对心率数据进行统计查询。
以下代码编译但在函数调用时会导致以下错误:
致命错误:在解包可选值时意外发现nil
此行发生错误:
let quantity : 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)
}
答案 0 :(得分:1)
result
参数不保证是非零的。如果它不是nil,你应该只打开并使用结果,否则检查error
以查看出错的地方。您可能会发生许多超出控制范围的错误(例如,在处理查询时设备可能会被锁定,或者执行查询的系统守护程序可能会崩溃)。
答案 1 :(得分:0)
我最终在这里采取了不同的方法,并且能够通过查询一组心率数据并取平均值来手动解决问题。
注意: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)
}