Updated: I am trying to call on a function that accesses the HealthKit and returns the number of steps taken that day.
I have created a function and now I am trying to call it. The code for the function is as follows:
//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)
}
I am creating a button action and inside it I am trying to call the todayTotalSteps function. I have enabled HealthKit permissions in a different function. Running the app on my iPhone 5 works fine until I add the function todayTotalSteps and the button with its action, then when I tap the button I added, I get the following error and nothing else happens. In the debug area it says:
"HealthkitAccess[267:13336] [query] Error activating query: Error Domain=com.apple.healthkit Code=5 "Authorization not determined" UserInfo={NSLocalizedDescription=Authorization not determined}"
The button function is written below:
@IBAction func getSteps(_ sender: Any) {
todayTotalSteps(input: "commands"){stepRetrieved in print(stepRetrieved)
}
I am using Swift 3, Xcode 8. I am new to swift and I would really appreciate any insight to get this to work! Thanks!