使用 Swift 从 HealthKit 读取日期间隔的步骤

Posted

技术标签:

【中文标题】使用 Swift 从 HealthKit 读取日期间隔的步骤【英文标题】:Reading steps for date intervals from HealthKit using Swift 【发布时间】:2016-08-02 06:00:36 【问题描述】:

我有这个方法可以从 HealthKit 中读取今天的步骤。

func todaySteps(completion: (Double, NSError?) -> () )
 // this function gives you all of the steps the user has taken since the beginning of the current day.

    let type = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount) // The type of data we are requesting


    let date = NSDate()
    print(date)
    let cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
    let newDate = cal.startOfDayForDate(date)
    print(newDate)
    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)
    

    executeQuery(query)

现在让我们说如果我想阅读从 2016 年 6 月 1 日到 2016 年 6 月 7 日每天的总步数

我该怎么做,请指导我谢谢

【问题讨论】:

【参考方案1】:

使用它来获取多个日期的步骤

func MultipleDaysStepsAndActivities(_ startDate:Date, completion: @escaping (NSDictionary, [HealthKitManuallActivity], NSError?) -> () ) 

    let calender = NSCalendar.current
    let now = Date()
    _ = calender.component(.year, from: now)

    let type = HKSampleType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount) // The type of data we are requesting
    let predicate = HKQuery.predicateForSamples(withStart: startDate, end: now, options: HKQueryOptions())

    var interval = DateComponents()
    interval.day = 1

    let query = HKStatisticsCollectionQuery(quantityType: type!, quantitySamplePredicate: predicate, options: [.cumulativeSum], anchorDate: startDate, intervalComponents:interval)

    query.initialResultsHandler =  query, results, error in

        if error != nil 
            print(error as Any)
            return
        

        var dict:[String:Double] = [:]

        if let myResults = results 
            myResults.enumerateStatistics(from: startDate, to: now) 
                statistics, stop in

                if let quantity = statistics.sumQuantity() 

                    let steps = quantity.doubleValue(for: HKUnit.count())
                    print("Steps = \(steps.rounded())")
                    dict[self.fmt.string(from: statistics.startDate)] = steps.rounded()
                
            
        

    

    execute(query)


【讨论】:

以上是关于使用 Swift 从 HealthKit 读取日期间隔的步骤的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 Swift 从 iOS HealthKit 应用程序读取心率?

如何使用 Swift 从 iOS HealthKit 应用程序读取心率?

Swift HealthKit 触发心率样本

Swift 2.0:读取 HealthKit 心率数据 - 在展开 Optional 时意外发现 nil

Swift 2.0:读取 HealthKit 心率数据 - 在展开 Optional 时意外发现 nil

每次使用 swift 在 HealthKit 中返回数字 0?