如何使用HealthKit快速获取步行和跑步距离 [英] How to get walking and running distance using HealthKit in swift
本文介绍了如何使用HealthKit快速获取步行和跑步距离的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在制作Health App.我想从Swift中的HealthKit
获取walkingRunningDistance
.但是,我有一个问题.返回值为0.0mile.
I'm making Health App. I want to get walkingRunningDistance
from HealthKit
in Swift. But, I have a problem. Return value is 0.0mile.
为什么返回值是0英里?
Why return value is 0 mile?
我的代码是这个.
func recentSteps3(completion: (Double, NSError?) -> () ){
let type = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDistanceWalkingRunning)
let date = NSDate()
let cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
let newDate = cal.startOfDayForDate(date)
let predicate = HKQuery.predicateForSamplesWithStartDate(newDate, endDate: NSDate(), options: HKQueryOptions.StrictStartDate)
let query = HKSampleQuery(sampleType: type!, predicate: predicate, limit: HKObjectQueryNoLimit, sortDescriptors: nil) { query, results, error in
var distance: Double = 0
if results?.count > 0
{
for result in results as! [HKQuantitySample]
{
distance += result.quantity.doubleValueForUnit(HKUnit.mileUnit())
}
}
completion(distance, error)
}
healthAuth.healthStore.executeQuery(query)
}
推荐答案
您的代码将在以下情况下返回值
Your code will return a value if
- 您已请求用户允许阅读 从HealthKit运行distanceWalkingRunning
- 用户已授予您的应用权限.
- You have requested permission from the user to read distanceWalkingRunning from HealthKit
- The user has granted your app permission.
否则,您的代码将返回0.
If not, your code will return 0.
要请求授权,您可以致电
To request authorization, you can call
func requestAuthorization(toShare typesToShare: Set<HKSampleType>?, read typesToRead: Set<HKObjectType>?, completion: @escaping (Bool, Error?) -> Swift.Void)
其中typesToRead
包含
let distanceType = HKSampleType.quantityType(forIdentifier: HKQuantityTypeIdentifier.distanceWalkingRunning)!
我相信使用HKStatisticsQuery或HKStatisticsCollectionQuery会更高效.这是一个例子.
I believe that using a HKStatisticsQuery or HKStatisticsCollectionQuery will be more efficient. Here is an example.
guard let type = HKSampleType.quantityType(forIdentifier: .distanceWalkingRunning) else {
fatalError("Something went wrong retriebing quantity type distanceWalkingRunning")
}
let date = Date()
let cal = Calendar(identifier: Calendar.Identifier.gregorian)
let newDate = cal.startOfDay(for: date)
let predicate = HKQuery.predicateForSamples(withStart: newDate, end: Date(), options: .strictStartDate)
let query = HKStatisticsQuery(quantityType: type, quantitySamplePredicate: predicate, options: [.cumulativeSum]) { (query, statistics, error) in
var value: Double = 0
if error != nil {
print("something went wrong")
} else if let quantity = statistics?.sumQuantity() {
value = quantity.doubleValue(for: HKUnit.mile())
}
DispatchQueue.main.async {
completion(value)
}
}
healthStore.execute(query)
这篇关于如何使用HealthKit快速获取步行和跑步距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文