Swift 3:从健康套件调用步骤计数查询
更新:我试图调用一个函数,该函数访问HealthKit并返回当天采取的步骤数 我已经创建了一个函数,现在我正在尝试调用它。该函数的代码如下所示:Swift 3:从健康套件调用步骤计数查询,swift,xcode,function,swift3,healthkit,Swift,Xcode,Function,Swift3,Healthkit,更新:我试图调用一个函数,该函数访问HealthKit并返回当天采取的步骤数 我已经创建了一个函数,现在我正在尝试调用它。该函数的代码如下所示: //Reading data from Health app. func todayTotalSteps (input: String, completion: @escaping (_ stepRetrieved: Double) -> Void){ // Define the Step Quantity Type. let
//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上运行应用程序可以正常工作,直到我今天添加了TotalSteps函数和按钮及其动作,然后当我点击我添加的按钮时,我得到以下错误,没有其他任何事情发生。在调试区域中,它显示:
“HealthkitAccess[267:13336][query]激活查询时出错:错误域=com.apple.healthkit代码=5“未确定授权”用户信息={NSLocalizedDescription=未确定授权}”
按钮功能写在下面:
@IBAction func getSteps(_ sender: Any) {
todayTotalSteps(input: "commands"){stepRetrieved in print(stepRetrieved)
}
我使用的是Swift 3,Xcode 8。我是斯威夫特的新手,我非常感谢任何能让这项工作成功的见解!谢谢 新的HK要求您在获取任何类型的数据之前,必须获得用户的许可。
@IBAction func getSteps(_ sender: Any) {
todayTotalSteps(input: "commands") { stepRetrieved in
print(stepRetrieved)
}
}
在新的更新中,他们提到:
“重要信息:在iOS 10.0上或之后链接的iOS应用程序必须包含在其
Info.plist文件它所包含的数据类型的使用说明码
需要访问,否则将崩溃。访问和更新HealthKit数据
具体而言,它必须包括NSHealthShareUsageDescription和
nshealth分别更新使用说明码。“
数一数你的花括号。你需要相同数量的开放式和封闭式花括号。您好,我以为我唯一的问题是无法调用按钮中的函数,但函数本身不起作用。你能重新看一下吗?谢谢