![](/img/trans.png)
[英]How to get real time Health updates from Apple watch, sync it with health kit and send it to server?
[英]Tell if a Health Kit sample came from an Apple Watch?
当源是Apple Watch时,Health App会显示Watch图标。
我只想获得Health App用来确定源类型的相同信息。 HKSource似乎没有提供。
自的iOS 9,类型的样品HKSample
具有属性device
类型的HKDevice
。
HKDevice
告诉您有关样本源设备的所有信息。
HKDevice.model
描述了硬件类型。 在撰写本文时,Apple没有记录Apple在HKDevice.model
使用的HKDevice.model
。 在我的实验中,我发现了“iPhone”和“Watch”的价值观。
我在我的应用程序中遇到了类似的问题,我们只需要提取仅适用于Apple iPhone和Apple Watch的步骤数据。 我搜索了很多,但在iOS 8.0中找不到任何答案,并找到了你的问题。
我已经找到了一种方法来区分手表和手机使用以下过程(可能不是最好的解决方案,但在我的情况下工作):
我注意到来自iPhone / Watch的所有步骤数据都具有以下bundleIdentifier格式:
com.apple.health.DeviceUUID
请注意,在Health应用程序中手动输入的数据的包标识符为com.apple.Health(大写为“H”)。
所以,首先,使用以下方法获取手机的设备名称:
NSString *deviceName = [[UIDevice currentDevice] name];
接下来,获取bundleIdentifier中前缀匹配为'com.apple.health'的所有源。 这应该为您提供iPhone和Apple手表作为有效来源,并忽略手动条目和所有其他应用程序。
接下来,检查源中的设备名称是否相同,并忽略该源(iPhone),另一个源应该是Apple Watch。
以下是获取源的示例源查询:
- (void)fetchSources
{
NSString *deviceName = [[UIDevice currentDevice] name];
NSMutableArray *dataSources = [[NSMutableArray alloc] init];
HKQuantityType *stepsCount = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
HKSourceQuery *sourceQuery = [[HKSourceQuery alloc] initWithSampleType:stepsCount
samplePredicate:nil
completionHandler:^(HKSourceQuery *query, NSSet *sources, NSError *error)
{
for (HKSource *source in sources)
{
//Ignore the iPhone as a source as the name of the device will watch with the source.
//The other device will be an Apple Watch
if ([source.bundleIdentifier hasPrefix:sourceIdentifier] && ![source.name isEqualToString:deviceName])
{
[dataSources addObject:source];
}
}
}];
[self.healthStore executeQuery:sourceQuery];
}
现在,您可以使用NSPredicate类为此数据提取源创建一个谓词:
NSPredicate *sourcesPredicate = [HKQuery predicateForObjectsFromSource:source];
请注意,我的第一个想法是匹配UUID,但是当我使用NSUUID类生成UUID时,它与拉出源中的包标识符中存在的UUID不匹配。
此外,您可以将手机名称更改为您想要的任何名称,它也会在Health应用程序中自动更新。
正如我所说,不是最好的解决方案,但对我有用,这是我能找到的唯一方法。 如果您能找到更好的解决方案,请告诉我。 谢谢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.