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

标签 ios swift nsdate healthkit hksamplequery

我有这个方法可以从 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)
}

现在假设我想读取从 1/jun/2016 到 7/june/2016 的每一天的总步数

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

最佳答案

用它来获取多个日期的步数

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)

}

关于ios - 使用 Swift 从 HealthKit 读取日期间隔的步骤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38712786/

相关文章:

ios - 我是否需要增量获取 CloudKit 更改和订阅?

ios - 通过 UITextView 内容大小调整 UITableView 单元格

android - Ionic 框架 facebook 登录集成

swift - 如何在 Swift 中以短格式获取当前日期

javascript - 在套接字 io 连接中设置用户名

Swift:更新 Xcode 时出错: 'could not find overload for ' & &' that accepts the supplied arguments'

ios - UIPickerView 作为多个 UITextField 的 inputView

drag-and-drop - 在 Swift 中拖放 - 注册拖动类型有问题吗?

iphone - 转换字符串日期格式

iphone - 使用 NSDateFormatter 解析 RFC 822 日期