我试图在 Apple Watch 复杂功能中显示用户的每日步数。我通过调用 HKHealthStore 的 requestAuthorizationToShareTypes 方法来设置我的课程,当首次将其添加到表盘时,复杂功能会正确显示步骤。但是,在进行健康包查询时,刷新永远不会成功。我怀疑这与 HealthKit 权限有关,因为 HKSampleQuery 的完成处理程序没有被调用。如果我只是注释掉 health kit 查询,那么我的代码会按预期刷新。有谁知道我可能会错过什么?或者如果复杂的后台刷新不允许访问 HealthKit?
这是有效的代码块:
/// Provide the entry that should currently be displayed.
/// If you pass back nil, we will conclude you have no content loaded and will stop talking to you until you next call -reloadTimelineForComplication:.
func getCurrentTimelineEntryForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationTimelineEntry?) -> Void) {
let calendar = NSCalendar.currentCalendar()
let now = NSDate()
var startDate: NSDate? = nil
var interval: NSTimeInterval = 0
let endDate = NSDate()
calendar.rangeOfUnit(NSCalendarUnit.Day, startDate: &startDate, interval: &interval, forDate: now)
// Show dummy step data...
let timelineEntry = self.buildTimelineEntry(complication, stepCount: 10, currentDateInterval: NSDate())
handler(timelineEntry)
}
这是不起作用的代码块。错误情况下的更新甚至不会被调用:
/// Provide the entry that should currently be displayed.
/// If you pass back nil, we will conclude you have no content loaded and will stop talking to you until you next call -reloadTimelineForComplication:.
func getCurrentTimelineEntryForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationTimelineEntry?) -> Void) {
let calendar = NSCalendar.currentCalendar()
let now = NSDate()
var startDate: NSDate? = nil
var interval: NSTimeInterval = 0
let endDate = NSDate()
calendar.rangeOfUnit(NSCalendarUnit.Day, startDate: &startDate, interval: &interval, forDate: now)
let predicate = HKQuery.predicateForSamplesWithStartDate(startDate, endDate: endDate, options: HKQueryOptions.StrictStartDate)
let sortDescriptor = NSSortDescriptor(key:HKSampleSortIdentifierStartDate, ascending: true)
let stepSampleType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount)!
let sampleQuery = HKSampleQuery(sampleType: stepSampleType, predicate: predicate, limit: 0, sortDescriptors: [sortDescriptor]) { (sampleQuery, results, error ) -> Void in
if error != nil {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let timelineEntry = self.buildTimelineEntry(complication, stepCount: 10, currentDateInterval: NSDate())
handler(timelineEntry)
})
return
}
self.currentSteps = [HKQuantitySample]()
if results != nil {
self.currentSteps = results as! [HKQuantitySample]
}
let countUnit = HKUnit(fromString: "count")
var stepCount = 0.0
var currentDate = now
for result in self.currentSteps {
stepCount += result.quantity.doubleValueForUnit(countUnit)
currentDate = result.endDate
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let timelineEntry = self.buildTimelineEntry(complication, stepCount: stepCount, currentDateInterval: currentDate)
handler(timelineEntry)
})
}
self.healthStore.executeQuery(sampleQuery)
}