HealthKit Swift getting today's steps

后端 未结 6 1497
灰色年华
灰色年华 2020-12-23 11:50

I am making a swift iOS app that integrates with a user\'s step count as reported by the Health app. I can easily find the user\'s step count in the last hour, using this as

6条回答
  •  感情败类
    2020-12-23 12:45

    The query you were using takes all of the user's recorded steps from Healthkit, not doing the smart filter-out of duplicative steps the Health app does. Instead, you want to get the aggregated step data that the Health app produces after combining steps from different sources to get an accurate tally.

    To do that, you can use this code:

    func recentSteps2(completion: (Double, NSError?) -> () )
    { // this function gives you all of the steps the user has taken since the beginning of the current day.
    
        checkAuthorization() // checkAuthorization just makes sure user is allowing us to access their health data.
        let type = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount) // The type of data we are requesting
    
    
        let date = NSDate()
        let cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
        let newDate = cal.startOfDayForDate(date)
        let predicate = HKQuery.predicateForSamplesWithStartDate(newDate, endDate: NSDate(), options: .None) // Our search predicate which will fetch all steps taken today
    
        // The actual HealthKit Query which will fetch all of the steps and add them up for us.
        let query = HKSampleQuery(sampleType: type!, predicate: predicate, limit: 0, sortDescriptors: nil) { query, results, error in
            var steps: Double = 0
    
            if results?.count > 0
            {
                for result in results as! [HKQuantitySample]
                {
                    steps += result.quantity.doubleValueForUnit(HKUnit.countUnit())
                }
            }
    
            completion(steps, error)
        }
    
        storage.executeQuery(query)
    }
    

提交回复
热议问题