我在应用程序中使用Health-kit来读取用户的步骤和活动。一切正常,但是我只想阅读自动检测到的活动和步骤。目前,我得到了健康应用程序手动输入或自动检测到的所有数据天气。到目前为止,这是我的代码

func todaySteps(completion: (Double, NSError?) -> () )
{
    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

    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)
}


但是,在哪里以及如何检查用户输入或自动检测到的数据?我也看到过This问题,但在Objective-C中却没有,我无法完全理解它,因此请引导我。

最佳答案

我自己解决了这个问题。这就是我的方法。

func todaySteps(completion: (Double, NSError?) -> () )
{
    let type = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount)

    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)

    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]
            {
                print("Steps \(result.quantity.doubleValueForUnit(HKUnit.countUnit()))")

                // checking and truncating manually added steps
                if result.metadata != nil {
                    // Theses steps were entered manually
                }
                else{
                    // adding steps to get total steps of the day
                    steps += result.quantity.doubleValueForUnit(HKUnit.countUnit())
                }

            }
        }
        completion(steps, error)
    }
    executeQuery(query)
}

10-06 13:04