iOS实战之用户交互:HealthKit

0

Prerequisite(预准备)

Enable HealthKit

如果希望在应用程序中使用HealthKit,首先需要在生成证书的时候勾选HealthKit选项。

Check availability(检查HealthKit可用性)

考虑到目前HealthKit仅仅可以在iPhone设备上使用,不能在iPad或者iPod中使用,所以在接入HealthKit代码之前最好检验下可用性:

if(NSClassFromString(@"HKHealthStore") && [HKHealthStore isHealthDataAvailable])
{
   // Add your HealthKit code here
}

Request authorization(请求授权)

由于HealthKit存储了大量的用户敏感信息,App如果需要访问HealthKit中的数据,首先需要请求用户权限。权限分为读取与读写权限(苹果将读写权限称为share)。请求权限还是比较简单的,可以直接使用requestAuthorizationToShareTypes: readTypes: completion: 方法。

HKHealthStore *healthStore = [[HKHealthStore alloc] init];

// Share body mass, height and body mass index
NSSet *shareObjectTypes = [NSSet setWithObjects:
                           [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyMass],
                           [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeight],
                           [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyMassIndex],
                           nil];

// Read date of birth, biological sex and step count
NSSet *readObjectTypes  = [NSSet setWithObjects:
                           [HKObjectType characteristicTypeForIdentifier:HKCharacteristicTypeIdentifierDateOfBirth],
                           [HKObjectType characteristicTypeForIdentifier:HKCharacteristicTypeIdentifierBiologicalSex],
                           [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount],
                           nil];

// Request access
[healthStore requestAuthorizationToShareTypes:shareObjectTypes
                                    readTypes:readObjectTypes
                                   completion:^(BOOL success, NSError *error) {

                                       if(success == YES)
                                       {
                                           // ...
                                       }
                                       else
                                       {
                                           // Determine if it was an error or if the
                                           // user just canceld the authorization request
                                       }

                                   }];

如上代码会调用下图这样的权限请求界面:

用户在该界面上可以选择接受或者拒绝某些对于读写健康数据的请求。在确定或者关闭请求界面之后,回调会被自动调用。

读写数据

从Health Store中读写数据的方法比较直接,HKHealthStore类是提供了很多便捷的方法读取基本的属性。不过如果需要以更多复杂的方式进行查询,可以使用相关的子类:HKQuery。

生理数据

性别与年龄

NSError *error;
HKBiologicalSexObject *bioSex = [healthStore biologicalSexWithError:&error];

switch (bioSex.biologicalSex) {
    case HKBiologicalSexNotSet:
        // undefined
        break;
    case HKBiologicalSexFemale:
        // ...
        break;
    case HKBiologicalSexMale:
        // ...
        break;
}

体重

// Some weight in gram
double weightInGram = 83400.f;

// Create an instance of HKQuantityType and
// HKQuantity to specify the data type and value
// you want to update
NSDate          *now = [NSDate date];
HKQuantityType  *hkQuantityType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyMass];
HKQuantity      *hkQuantity = [HKQuantity quantityWithUnit:[HKUnit gramUnit] doubleValue:weightInGram];

// Create the concrete sample
HKQuantitySample *weightSample = [HKQuantitySample quantitySampleWithType:hkQuantityType
                                                                 quantity:hkQuantity
                                                                startDate:now
                                                                  endDate:now];

// Update the weight in the health store
[healthStore saveObject:weightSample withCompletion:^(BOOL success, NSError *error) {
    // ..
}];

运动数据

步数

// Set your start and end date for your query of interest
NSDate *startDate, *endDate;

// Use the sample type for step count
HKSampleType *sampleType = [HKSampleType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];

// Create a predicate to set start/end date bounds of the query
NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:startDate endDate:endDate options:HKQueryOptionStrictStartDate];

// Create a sort descriptor for sorting by start date
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierStartDate ascending:YES];


HKSampleQuery *sampleQuery = [[HKSampleQuery alloc] initWithSampleType:sampleType
                                                             predicate:predicate
                                                                 limit:HKObjectQueryNoLimit
                                                       sortDescriptors:@[sortDescriptor]
                                                         resultsHandler:^(HKSampleQuery *query, NSArray *results, NSError *error) {
                                                            
                                                             if(!error && results)
                                                             {
                                                                 for(HKQuantitySample *samples in results)
                                                                 {
                                                                     // your code here
                                                                 }
                                                             }
                                                             
                                                         }];

// Execute the query
[healthStore executeQuery:sampleQuery];

如果觉得我的文章对你有用,请随意赞赏

你可能感兴趣的

粥米鱼 · 2015年10月24日

很好的文章呢,请问愿意分享一份去社区给更多的人看到么 http://swiftcn.io

回复

anyway · 2017年02月08日

问一下, HKQuantitySample *stepConsumedSample = [HKQuantitySample quantitySampleWithType:stepConsumedType quantity:stepQuantityConsumed startDate:startDate endDate:endDate device:device metadata:nil];
我用这个方法把步数已经修改,为什么微信上步数没有增加

回复

载入中...