1、HealthKit的授权
//获取读取的授权
lethealthKitTypesToRead =NSSet(array:[
//出生日期
HKObjectType.characteristicTypeForIdentifier(HKCharacteristicTypeIdentifierDateOfBirth)!,
//血液类型
HKObjectType.characteristicTypeForIdentifier(HKCharacteristicTypeIdentifierBloodType)!,
//性别
HKObjectType.characteristicTypeForIdentifier(HKCharacteristicTypeIdentifierBiologicalSex)!,
//体重
HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass)!,
//身高
HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeight)!,
HKObjectType.workoutType()
])
//获取写出的授权,也是需要表明相关的写入对象
lethealthKitTypeToWrite =NSSet.init(array: [
HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMassIndex)!,
HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierActiveEnergyBurned)!,
HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDistanceWalkingRunning)!,
HKQuantityType.workoutType()
])
将你想使用的相应的数据装入集合中。
验证健康数据是否可用
if !HKHealthStore.isHealthDataAvailable(){
//TO DO SOME
}
开始授权
let healthKitStore:HKHealthStore=HKHealthStore()
healthKitStore.requestAuthorizationToShareTypes(healthKitTypeToWrite as? Set, readTypes: healthKitTypesToRead as? Set) { (success, error) in {}
2、获取相关信息
对于一些简单的数据(非集合的)如:个人的基本信息。可以直接通过HKHealthStore提供的相关方法直接获得
let healthKitStore:HKHealthStore=HKHealthStore()
//e.g
var age: Int
let birthDay: NSDate?
do{
birthDay =tryhealthKitStore.dateOfBirth()
}catch{
birthDay =nil
print("read Date Data faild")
}
ifbirthDay !=nil
{
lettoday =NSDate()
letdifferenceComponents =NSCalendar.currentCalendar().components(.NSYearCalendarUnit, fromDate: birthDay!, toDate: today, options:NSCalendarOptions(rawValue:0))
age = differenceComponents.year
}
而对于一些数据集组成的数据来说需要借助HKSampleQuery来进行相关的查询
@method initWithSampleType:predicate:limit:sortDescriptors:resultsHandler:
@abstract Returns a query that will retrieve HKSamples matching the given predicate.
@param sampleType The type of sample to retrieve.
@param predicate The predicate which samples should match.
@param limit The maximum number of samples to return.Pass HKObjectQueryNoLimit for no limit.
@param sortDescriptors The sort descriptors to use to order the resulting samples.
@param resultsHandler The block to invoke with results when the query has finished executing.
*/
public init(sampleType:HKSampleType, predicate:NSPredicate?, limit:Int, sortDescriptors: [NSSortDescriptor]?, resultsHandler: (HKSampleQuery, [HKSample]?,NSError?) ->Void)
}
其上的方法通过相应的参数来控制查询结果
//sampleType:HKSampleType
let sampleType =HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeight)
通过identifier来控制查询的是那一类的数据
通过predicate:NSPredicate来进行相关的筛选
//e.g 关于NSDate的筛选
//endDate为返回结果中的属性之一
NSPredicate*predicate_date =
[NSPredicatepredicateWithFormat:@"endDate >= %@ AND endDate <= %@", today,afterDay];
通过sortDescriptors: [NSSortDescriptor]?来进行排序处理
通过limit:Int来限制最大的数据个数
//今天(04.11)就先到这点吧。。。
//第一次发完善中吧
网友评论