我尝试选择HealthKit activitySummaries(iOS 9.3新增功能)
@available(iOS 9.3, watchOS 2.2, *)
func selectTodayActivitySummary (store: HKHealthStore, completion: ((summaryQuery: HKActivitySummaryQuery, summary: [HKActivitySummary]?, error: NSError?) -> Void)) {
guard let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian) else {
fatalError("*** This should never fail. ***")
}
let endDate = NSDate()
guard let startDate = calendar.dateByAddingUnit(.Day, value: -7, toDate: endDate, options: []) else {
fatalError("*** unable to calculate the start date ***")
}
let units: NSCalendarUnit = [.Day, .Month, .Year, .Era]
let startDateComponents = calendar.components(units, fromDate: startDate)
let endDateComponents = calendar.components(units, fromDate:endDate)
// Create the predicate for the query
let summariesWithinRange = HKQuery.predicateForActivitySummariesBetweenStartDateComponents(startDateComponents, endDateComponents: endDateComponents)
//let summariesAtDate = HKQuery.predicateForActivitySummaryWithDateComponents(startDateComponents)
let query = HKActivitySummaryQuery(predicate: summariesWithinRange) {
(summaryQuery: HKActivitySummaryQuery, summary: [HKActivitySummary]?, error: NSError?) in
completion(summaryQuery: summaryQuery, summary: summary, error: error)
}
store.executeQuery(query)
}
当我将此代码作为单元测试运行时,我得到一个例外 “NSInvalidArgumentException”,“startDateComponents:Date components需要一个日历。”
这段代码有什么问题? 此代码几乎完全来自https://developer.apple.com/library/prerelease/ios/documentation/HealthKit/Reference/HKActivitySummaryQuery_Class/index.html
使用XCode 7.3 beta 4(7D152p),iPhone 6s Plus 9.3模拟器进行测试
答案 0 :(得分:2)
calendar
属性在startDateComponents
和endDateComponents
上必须是非零的(否则您希望解释组件的日历不明确)。很遗憾,当您致电NSCalendar
时,components(_, fromDate:)
并未填充该属性,因此您需要手动执行此操作:
let startDateComponents = calendar.components(units, fromDate: startDate)
startDateComponents.calendar = calendar
let endDateComponents = calendar.components(units, fromDate:endDate)
endDateComponents.calendar = calendar