【问题标题】:How to get cycling duration from HealthKit for ios app using Swift如何使用 Swift 从适用于 ios 应用程序的 HealthKit 获取循环持续时间
【发布时间】:2016-07-12 07:29:34
【问题描述】:

我正在创建一个从 health-Kit 读取数据的应用程序。我能够读取步数、跑步+步行等。现在我正在尝试读取骑车的日期和持续时间。这就是我用于跑步+步行的方法

func readDistanceWalkingRunning(completion: (([AnyObject]!, NSError!) -> Void)!) {
    let runningWalking = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDistanceWalkingRunning)
    let predicate = HKQuery.predicateForSamplesWithStartDate(NSDate().dateByAddingTimeInterval(-86400.0), endDate: NSDate(), options: HKQueryOptions.None)

    let stepsSampleQuery = HKSampleQuery(sampleType: runningWalking!,
                                         predicate: predicate,
                                         limit: 100,
                                         sortDescriptors: nil)
    { [weak self] (query, results, error) in

        if let results = results as? [HKQuantitySample] {

            for result in results {
                print(" Distance was " + " \(result.quantity.doubleValueForUnit(HKUnit.mileUnit())) ")
                print("Date was " + "\(result.startDate)")

            }
        }
    }

    // Don't forget to execute the Query!
    executeQuery(stepsSampleQuery)
}

一切都很好,但是当我尝试使用下面的代码读取骑行距离时,我得到的结果为零。骑行数据显示在 appleHealth 应用程序中,但为什么我的结果为 nil ?请帮忙

    func readDistanceCycling(completion: (([AnyObject]!, NSError!) -> Void)!) {
    let distanceCycling = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDistanceCycling)
    let predicate = HKQuery.predicateForSamplesWithStartDate(NSDate(), endDate: NSDate(), options: HKQueryOptions.None)

    let query = HKSampleQuery(sampleType: distanceCycling!, predicate: predicate, limit: 100, sortDescriptors: nil, resultsHandler: { query, result, error in


if result != nil
{
    print("We have some Data")
}
else
{
    print("Result is nil")
}

if let results = result as? [HKQuantitySample] {

    for result in results {
        print(" Quantity type " + " \(result.quantityType) ")
        print("Date was " + "\(result.startDate)")

    }
}
})

    executeQuery(query)
    }


    }

【问题讨论】:

    标签: ios swift swift2 healthkit hksamplequery


    【解决方案1】:

    使用下面给出的函数。它为您提供最少 7 条记录。您也可以根据自己的要求进行更改。

    func getHealthDataValue ( HealthQuantityType : HKQuantityType , strUnitType : String , GetBackFinalhealthData: ((( healthValues : [AnyObject] ) -> Void)!) )
    {          
        if let heartRateType = HKQuantityType.quantityTypeForIdentifier(HealthQuantityType.identifier)
        {
            if (HKHealthStore.isHealthDataAvailable()  ){
    
                let sortByTime = NSSortDescriptor(key:HKSampleSortIdentifierEndDate, ascending:false)
    
                //            let timeFormatter = NSDateFormatter()
                //            timeFormatter.dateFormat = "hh:mm:ss"
                //yyyy-MM-dd'T'HH:mm:ss.SSSZZZZ
    
                let dateFormatter = NSDateFormatter()
                dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
    
            let query = HKSampleQuery(sampleType:heartRateType, predicate:nil, limit:7, sortDescriptors:[sortByTime], resultsHandler:{(query, results, error) in
    
                guard let results = results else {
    
                    //include the healthkit error in log
                    if let errorDescription = error!.description as String?
                    {
    
                        GetBackFinalhealthData (healthValues: ["nodata"])
                    }
                    return
                }
    
                var arrHealthValues     = [AnyObject]()
    
                for quantitySample in results {
                    let quantity = (quantitySample as! HKQuantitySample).quantity
                    let healthDataUnit : HKUnit
                    if (strUnitType.length > 0 ){
                        healthDataUnit = HKUnit(fromString: strUnitType)
                    }else{
                        healthDataUnit = HKUnit.countUnit()
                    }
    
                    let tempActualhealthData = "\(quantity.doubleValueForUnit(healthDataUnit))"
                    let tempActualRecordedDate = "\(dateFormatter.stringFromDate(quantitySample.startDate))"
                    if  (tempActualhealthData.length > 0){
                        let dicHealth : [String:AnyObject] = [HealthValue.kIdentifierValue :tempActualhealthData , HealthValue.kRecordDate :tempActualRecordedDate , HealthValue.kIdentifierDisplayUnit : strUnitType ]
    
                        arrHealthValues.append(dicHealth)
                    }
                }
    
                if  (arrHealthValues.count > 0)
                {
                    GetBackFinalhealthData (healthValues: arrHealthValues)
                }
                else
                {
                    GetBackFinalhealthData (healthValues: [HealthValue.kNoData])
                }
            })
            (self.HealthStore as! HKHealthStore).executeQuery(query)
        }
    }
    

    }

    使用上述功能如下。 这里需要传入类型和单位。

    self.getHealthDataValue(HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBloodPressureDiastolic), strUnitType: "mmHg"
                    ) { (arrHealth) -> Void in                  
                }
    

    【讨论】:

    • 它会给我骑行记录吗? :-o
    • 这个方法给你想要的一切。
    • 但是你需要正确调用方法
    • 我是初学者,请您指导我如何使用您的方法获取自行车记录?
    • 在哪里声明了** GetBackFinalhealthData**?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-31
    相关资源
    最近更新 更多