更新:我正在尝试调用访问HealthKit的函数,并返回当天所执行的步骤数。
我创建了一个函数,现在我试着调用它。该函数的代码如下:
//Reading data from Health app.
func todayTotalSteps (input: String, completion: @escaping (_ stepRetrieved: Double) -> Void){
// Define the Step Quantity Type.
let stepsCount = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)
// Get the start of the day.
let date = NSDate()
let calendar = Calendar(identifier: Calendar.Identifier.gregorian)
let newDate = calendar.startOfDay(for: date as Date)
let yesterday = NSCalendar.current.date(byAdding: .day, value: -1, to: Date())
let now = Date()
// Set the predicates & interval
let predicate = HKQuery.predicateForSamples(withStart: newDate as Date, end: NSDate() as Date, options: .strictStartDate)
let interval: NSDateComponents = NSDateComponents()
interval.day = 1
//Perform the Query
let query = HKStatisticsCollectionQuery(quantityType: stepsCount!, quantitySamplePredicate: predicate, options: [.cumulativeSum], anchorDate: newDate as Date, intervalComponents: interval as DateComponents)
query.initialResultsHandler = {query, results, error in
if error != nil {
// Something went wrong.
return
}
if let myResults = results{
myResults.enumerateStatistics(from: yesterday! as Date, to: now as Date){
statistics, stop in
if let quantity = statistics.sumQuantity(){
let steps = quantity.doubleValue(for: HKUnit.count())
print("Steps = \(steps)")
completion(steps)
}
}
}
}
healthStore.execute(query)
}
我正在创建一个按钮动作,在其中我试图调用todayTotalSteps函数。我在另一个函数中启用了HealthKit权限。在我的iPhone 5上运行应用程序工作正常,直到我添加函数todayTotalSteps和按钮及其动作,然后当我点击我添加的按钮时,我得到以下错误,没有其他任何事情发生。在调试区域中,它说:
" HealthkitAccess [267:13336] [query]激活查询时出错:错误Domain = com.apple.healthkit Code = 5"授权未确定" UserInfo = {NSLocalizedDescription =授权未确定}"
按钮功能如下:
@IBAction func getSteps(_ sender: Any) {
todayTotalSteps(input: "commands"){stepRetrieved in print(stepRetrieved)
}
我正在使用Swift 3,Xcode 8.我是swift的新手,我真的很感激有任何见解让这个工作!谢谢!
答案 0 :(得分:1)
@IBAction func getSteps(_ sender: Any) {
todayTotalSteps(input: "commands") { stepRetrieved in
print(stepRetrieved)
}
}
答案 1 :(得分:1)
新的HK要求您在获取任何类型的数据之前请求用户的许可。 在他们的新更新中,他们提到:
“重要”iOS 10.0上或之后链接的iOS应用必须包含在其中 Info.plist文件用于数据类型的用法描述键 需要访问或它将崩溃。访问和更新HealthKit数据 具体而言,它必须包括NSHealthShareUsageDescription和 分别为NSHealthUpdateUsageDescription键。“ https://developer.apple.com/reference/healthkit