-1

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!

user3546200
  • 269
  • 1
  • 3
  • 10

2 Answers2

1
@IBAction func getSteps(_ sender: Any) {
    todayTotalSteps(input: "commands") { stepRetrieved in
        print(stepRetrieved) 
    }
}
Benzi
  • 2,439
  • 18
  • 25
  • Hello, I thought that my only problem was with not being able to call the function in my button but the function itself does not work. Would you be able to re-look at it? Thanks! – user3546200 Feb 07 '17 at 14:52
1

The new HK requires you to ask for the user's permission before fetching any sort of data. In their new update, they mentioned:

"Important An iOS app linked on or after iOS 10.0 must include in its Info.plist file the usage description keys for the types of data it needs to access or it will crash. To access and update HealthKit data specifically, it must include the NSHealthShareUsageDescription and NSHealthUpdateUsageDescription keys, respectively." https://developer.apple.com/reference/healthkit

Sun.wc
  • 11
  • 3