HealthKit Swift getting today's steps

后端 未结 6 1496
灰色年华
灰色年华 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

    For swift 4.2

    1) Get HealthKitPermission

    import HealthKit
    
    func getHealthKitPermission() {
    
        delay(0.1) {
            guard HKHealthStore.isHealthDataAvailable() else {
                return
            }
    
            let stepsCount = HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)!
    
            self.healthkitStore.requestAuthorization(toShare: [], read: [stepsCount]) { (success, error) in
                if success {
                    print("Permission accept.")
                }
                else {
                    if error != nil {
                        print(error ?? "")
                    }
                    print("Permission denied.")
                }
            }
        }
    }
    

    2) To get steps count for specific date

    func getStepsCount(forSpecificDate:Date, completion: @escaping (Double) -> Void) {
            let stepsQuantityType = HKQuantityType.quantityType(forIdentifier: .stepCount)!
            let (start, end) = self.getWholeDate(date: forSpecificDate)
    
            let predicate = HKQuery.predicateForSamples(withStart: start, end: end, options: .strictStartDate)
    
            let query = HKStatisticsQuery(quantityType: stepsQuantityType, quantitySamplePredicate: predicate, options: .cumulativeSum) { _, result, _ in
                guard let result = result, let sum = result.sumQuantity() else {
                    completion(0.0)
                    return
                }
                completion(sum.doubleValue(for: HKUnit.count()))
            }
    
            self.healthKitStore.execute(query)
        }
    
        func getWholeDate(date : Date) -> (startDate:Date, endDate: Date) {
            var startDate = date
            var length = TimeInterval()
            _ = Calendar.current.dateInterval(of: .day, start: &startDate, interval: &length, for: startDate)
            let endDate:Date = startDate.addingTimeInterval(length)
            return (startDate,endDate)
        }
    

    How to use

    self.getStepsCount(forSpecificDate: Date()) { (steps) in
                    if steps == 0.0 {
                        print("steps :: \(steps)")
                    }
                    else {
                        DispatchQueue.main.async {
                            print("steps :: \(steps)")
                        }
                    }
                }
    

提交回复
热议问题