[英]How to detect if HealthKit data is set from a device?
I'm trying to fetch user steps from HealthKit and realised that users can add manually steps which I don't want to fetch.我试图从 HealthKit 获取用户步骤并意识到用户可以手动添加我不想获取的步骤。 (For instance if they're cheating and setting 50k steps on one day).
(例如,如果他们作弊并在一天内设置 50k 步)。
So I was thinking for a solution how to solve this problem and found out that maybe I could just filter all the result and fetch the data if the data was set by a device.所以我正在考虑如何解决这个问题的解决方案,并发现如果数据是由设备设置的,也许我可以过滤所有结果并获取数据。 I mean it could be set by an iPhone, but it can also be set by an Apple Watch.
我的意思是它可以由 iPhone 设置,但也可以由 Apple Watch 设置。
So when the data are set by a device, we can see more information from the device in the Health-app rather than a user whom setting the data manually.所以当数据由设备设置时,我们可以在Health-app中看到更多来自设备的信息,而不是手动设置数据的用户。
The question is: How do I find if there are a device in the result?问题是:如何查找结果中是否有设备?
func getSteps(completion: @escaping (Double, Error?) -> ()) {
let stepsQuantityType = HKQuantityType.quantityType(forIdentifier: .stepCount)!
let query = HKSampleQuery(sampleType: stepsQuantityType, predicate: nil, limit: 0, sortDescriptors: nil){ query, results, error in
if let error = error {
// Handle error
} else if let results = results, !results.isEmpty {
for result in results {
// Detect and add result if result is from a device
}
}
}
HKHealthStore().execute(query)
}
I just realised that I can detect if a device does exist by result.device
where device
is an optional value.我刚刚意识到我可以通过
result.device
检测设备是否存在,其中device
是可选值。 By doing so I can check if the value is nil
or not.通过这样做,我可以检查该值是否
nil
。
func getSteps(completion: @escaping (Double, Error?) -> ()) {
let stepsQuantityType = HKQuantityType.quantityType(forIdentifier: .stepCount)!
let query = HKSampleQuery(sampleType: stepsQuantityType, predicate: nil, limit: 0, sortDescriptors: nil){ query, results, error in
if let error = error {
// Handle error
} else if let results = results, !results.isEmpty {
for result in results {
if result.device != nil {
// Result is from a device
} else {
// Not a device
}
}
}
}
HKHealthStore().execute(query)
}
let predicateAvoidManuallyLoggedData = HKQuery.predicateForObjects(withMetadataKey: HKMetadataKeyWasUserEntered, operatorType: .notEqualTo, value: true)
use above predicate with HKSample or Statistics queries.将上述谓词与 HKSample 或 Statistics 查询一起使用。
you may also combine predicates like this你也可以组合这样的谓词
let predicate = NSCompoundPredicate(andPredicateWithSubpredicates:
[predicateSource, predicateTimePeriod, predicateAvoidManuallyLoggedData])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.