澳门威利斯人_威利斯人娱乐「手机版」

来自 威利斯人娱乐 2020-05-01 05:34 的文章
当前位置: 澳门威利斯人 > 威利斯人娱乐 > 正文

iOS修改步数,iOS关于HealthKit使用的主要对象及设

不等的健康应用供给大致能够分成二种

图片 1

在一中已经能够因而HKHealthStore的一些简易的API得到部分简便的数码以致由此HKSampleQuery及

1.总计解析 (Statistical Analysis卡塔尔(قطر‎2.同意客户输入设备(Enter Information卡塔尔国3.允许来自第三方的装置数据(Application From Health Providers卡塔尔国为此,apple开垦了Healthkit来拍卖这几个须求

只得校正健康应用中的步数哦

public init(sampleType:HKSampleType, predicate:NSPredicate?, limit:Int, sortDescriptors: [NSSortDescriptor]?, resultsHandler: (HKSampleQuery, [HKSample]?,NSError?) ->Void)

}

在分裂的国家,对同叁个概念有着不一致的心路单位。所以在HealthKit中,提议了HKUnit的定义。他正是为着救助开垦者做单位调换的。HKUnit代表了贰个在心胸标准或单位系统中的特定单位

1)导入头文件

来得到一些集结数据(运动的步数等以时日为单位的),接下去来品尝着相HKHealthStore中写入数据。

1.1 HKUnit
HKUnit *g = [HKUnit gramUnit]; //克HKUnit *dL = [HkUnit literUnitWithMetricPrefix:HKMetricPrefixDeci];//分升HKUnit *gPerdL = [g unitDivideByUnit:dL]; // 克/分升 g/dL//对于复杂的组合单位,也可以使用这种方式创建HKUnit *gPerdL = [HKUnit unitFromString:@"g/dL"];

#import <HealthKit/HealthKit.h>

3、健康数据的写入

1、简单多少的写入利用HKHealthStore

/*!

@method saveObject:withCompletion:

@abstract Saves an HKObject.

@discussion After an object is saved, on subsequent retrievals the sourceRevision property of the object will be set

to the HKSourceRevision representing the version of the application that saved it.

If the object has an HKObjectType property, then in order to save an object successfully the application

must first request authorization to share objects with that type.Saving an object with the same unique

identifier as another object that has already been saved will fail.When the application attempts to

save multiple objects, if any single object cannot be saved then none of the objects will be saved.

The operation will fail if the objects array contains samples with endDates that are older than the date

returned by earliestPermittedSampleDate.

This operation is performed asynchronously and the completion will be executed on an arbitrary

background queue.

*/

public func saveObject(object:HKObject, withCompletion completion: (Bool,NSError?) ->Void)

来写入叁个HKQuantitySample对象,

如何init一个HKQuantitySample对象

/*!

@method quantitySampleWithType:quantity:startDate:endDate:

@abstract Creates a new HKQuantitySample with the given type, quantity, start date, and end date.

@discussion The quantity must have a unit that is compatible with the given quantity type.

See -[HKQuantityType isCompatibleWithUnit:].

*/

public convenience init(type quantityType:HKQuantityType, quantity:HKQuantity, startDate:NSDate, endDate:NSDate)

HKQuantityType的init

public class func quantityTypeForIdentifier(identifier:String) ->HKQuantityType?

HKQuantity的init

/*!

@method quantityWithUnit:doubleValue:

@abstract Returns a new object representing a quantity measurement with the given unit.

*/

public convenience init(unit:HKUnit, doubleValue value:Double)

startDate与endDate是插入这条数据的开端时间与甘休时间的,健康数据中的数据是以时日段分布的,所以要求那八个参数。

平时来讲给出写入身体高度体重指数的例证

func saveBMISample(bmi:Double, date:NSDate) ->Void{

  let bmiType =HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMassIndex)

  let bmiQuantity =HKQuantity(unit:HKUnit.countUnit(), doubleValue: bmi)

  let bmiSample =HKQuantitySample(type: bmiType!, quantity: bmiQuantity, startDate: date, endDate: date)

  healthKitStore.saveObject(bmiSample) { (success, error)in

  if error !=nil {

    print("error save BMI Sample:(error?.localizedDescription)")

  }else{

   print("BMI sample save successfully!")

   }

 }

}


Health基特殊教育程 Swift版:练习音信

1.2 HKQuantity

他得以用于进行单位调换

HKUnit *gramUnit = [HKUnit gramUnit];HKQuantity *grams = [HKQuantity quantityWithUnit:gramUnit doubleValue:20]; //20克double kg = [grams doubleValueForUnit:[HKUnit unitFormString:@"kg"]];//转换为了0.02kg

而是否负有的单位都以可以如此进行更改的,借使转正为一个不相配的单位时,就能够报错。所以大家得以应用下边包车型客车章程开展预推断。

BOOL kgCompatible = [grams isCompatibleWithUnit:[HKUnit unitFromString:@"kg"]]; // YESBOOL kgCalComtible = [grams isCompatibleWithUnit:[HKUnit kilocalorieUnit]]; // NO

也正是说HKQuantity正是带有单位的数量值

2卡塔尔(قطر‎开端化全局变量

1.3 HKObjectType

Object types代表了HealthKit中的全数数据类型。在HealthKit中有超过常规60种等级次序,大繁多的门类都会组成到她协和类中。全部的这几个类,都以世襲于HKObjectType。全数的类分为多个着力大类。HKCharacteristicType:他代表一种不会转移的局地类型,比方生辰、性别等。HKSampleType:代表会随即间退换的类别,它们能在自然特定的光阴点里获取的到品种的样书。在此个项目上边又分为两种等级次序1>HKQuantityType ,比方血压2>HKCategoryType,代表可以分类的门类,譬喻睡眠深入分析。具体组织如图1

图片 2图1.png

KHObjectType的创设:每一项别型皆有个别她本身的identifier。当然你不能够创建和睦的objectType和对应的identifier。不过我们得以知道下他的布局准则。

HKQuantityTypeIdentifierHeartRateHKQuantityTypeIdentifier:代表他归于那连串型的数据HeartRate :代表她的名字

借使您有了有些项指标identifier,你就能够运用布局方法举办创办

 (HKQuantityType *)quantityTypeForIdentifier:(NSString *)identifier; (HKCategoryType *)categoryTypeForIdentifier:(NSString *)identifier; (HKCharacteristicType *)characteristicTypeForIdentifier:(NSString *)identifier;//显然三种构造方法,对应了三种不同的类型

@property (nonatomic) HKHealthStore *healthStore;

1.4 HKObject

在HealthKit中的全数存储数据都以HKObject的子类,具体社团如下图2

图片 3图2

HKQuantitySample有quantityType和quantity三个属性。qantityType代表了那个指标数据归属那连串型,quantity代表了切实可行的数值和单位。quantity的单位和quantityType须要非常。每多少个quantity type都对应了一种特定的单位。若无对应,则会抛出相当。如图3

图片 4图3.png

HKCategorySample和HKQuantitySample形似,他也许有categoryType代表她归属那体系型的多少,同时他有value值。这里要切记categoryType是一种能够的数值都以足以被枚举出来的。所以,每种类型都有一套对应的枚举值,value值必需对应内部的一个数值,若是一种现身了老大的数值,就可以报错。见图4

图片 5图4.png

那几个项目都是持续自HK萨姆ple,因为sample一种能够在一准期刻展开取样的的多寡,所以,他有startDate和endDate。对于有个别数据,譬如果您想取得体重这种及时性相当的高的值(总不可能取得一段时间的体重吧State of Qatar,所以他的startDate和endDate是一律的,而对于这种读取一定期期内的数值的数据类型,他们的startDate和endDate会差别等。各个sample也都有sampleType属性,他的其实类型和子类的type类型相像。如图5

图片 6图5.png

以上者那几个都以继承于HKObject类型,每一种Objec类型都有叁个UUID类型的习性,他是其一sample的独一标记。他也会有source属性,他记下了数额的来源。metadata对象是NSDictionary类型的属性,所以能够在里头存放纵何你想存放的数额,这么些脾性首若是为着扩展打算的。苹果也开辟者希图了有些metadatakey。如图6

图片 7图6.png

Create an HKObject

NSString * identifier = HKQuantityTypeIdentifierBodyTemperature;HKquantityType * tempType = [HKObjectType quantityTypeForIdentifier:identifier];HKQuantity * myTemp = [HKQuantity quantityWithUnit: [HKUnit degreeFahrenheiUnit] doubleValue:98.6];NSDictionary *meta = @{HKMetadataKeyBodyTemperatureSensorLocation : @(HKBodyTemperatureSensorLocationEar)};HKQuantitySample *temperatureSample = [HKQuantitySample quantitySampleWithType:tempType quantity:myTemp startDate:[NSDate date] endDate:[NSDate date] metadate:meta];

</br>

self.store = [[HKHealthStore alloc] init];...HKQuantitySample *mySample = [self newSample];[self.store saveObject:mySample withCompletion:^(BOOL success,NSError *error){if  { NSLog(@"object saved!");}}];

</br>

3)获取步数 刷新分界面

3.1 Characteristics

后面讲到,HKCharacteristicType是一种为主不改变的数据类型,所以我们得以平昔去赢得相应的数量,比方,生辰、血型等

NSError *error;NSDate *dateOfBirth = [self.store dateOfBirthWithError:&error];

- (void)getStepsFromHealthKit{

3.2 Queries

富有的Query都世襲自HKQuery

@interface HKQuery//注定要检索的数据类型@property  HKSampleType *sampleType//过滤返回的数据@Property  NSPredicate *predicate@end创建Predicate的几种方式//1.直接是使用构造方法[NSPredicate predicateWithFormat:@"%K > %@", HKPredicateKeyPathQuantity,weight];//2.更加简便的方式NSPredicateOperatorType greaterThan = NSGreaterThanPredicateOperatorType;[HKQuery perdicateForQuantitySampleWithOperatorType:greaterThan quantity:weight];

HKQuantityType *stepType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];

3.2.1 HKSampleQuery

Limit:每一种query都有个limit值,他点名了诉求再次回到值的数目,假使您不想节制检索的结果,你可以安装limit值为HKObjectQueryNoLimit。Sort Order:决定再次来到的多少的排列顺序的数组。

//Code demoHKQuantityType *bloodSugar = ...NSString *endKey = HKSampleSortIdentifierEndDate;NSSortDescriptor *endDate = [NSSortDescriptor sortDescriptorWithKey:endKey ascending:NO];HKSampleQuery *query = [[HKSampleQuery alloc] initWithSampleType:bloodSugar perdicate:nil sortDescriptor:@[endDate] resultsHandle:^(HKSampleQuery * query, NSArray *results, NSError *error){ HKQuantitySample *sample = [results lastObject]; NSLog(@"Sample: %@",sample);}]

[self fetchSumOfSamplesTodayForType:stepType unit:[HKUnit countUnit] completion:^(double stepCount, NSError *error) {

3.2.2 HKObserverQuery

他会监听数据库中的数据变动。所以当四个新的数码被抬高或移除的时候都会被调用。

HKQuantityType *bloodSugar = ...HKObserverQuery *query;query = [HKObserveQuery alloc] initWithSampleType:bloodSugar perdicate:nil updateHandler:^(HKObserverQuery *query, HKObserverCompletionHandler handler, NSError *error){ NSLog(@"Updated");}

dispatch_async(dispatch_get_main_queue(), ^{

3.2.3 HKAnchoredObectQuery

Anchor是你见的尾声一条数据,当anchor为0时,表示还还未有安装anchor,当每二回回调的时候会回来给您一个新的anchor

self.lastAnchor = 0...HKQuantityType *bloodSugar = ...HKAnchoredObjectQuery *query;query = [[HKAnchoredObjectQuery alloc] initWithType:bloodSugar perdicate:nil anchor:self.lastAnchor limit:HKObjectQueryLimit completionHandler:^(HKAnchoredObjectQuery *query, NSArray *results, NSUInter newAnchor, NSError *error){ self.lastAnchor = newAnchor;}];

</br>

@interface HKHealthStore: NSObject- executeQuery:(HKQuery *)query;- stopQuery:(HKQuery *)query;@end

stopQuery方法能够在任什么时候候调用,他回打消当前的搜寻操作,并阻挠其回调。你能够调用自便次数的stopQuery,不过只可以在上二个query停止前,调用贰次query。平日状态下,检索实行一回就可以告一段落。可是像ObserverQuery那样的long runing query(这里仍旧原来的书文相比有味道)必要手动去休息。</br>

HKStatistics叁个HKStatistics对象是各类总结数据的汇聚,举个例子sum、min、max 和 average。你可以总括全数的数码,大概只计算特定来源的数额⚠️注意,Statstics只对quantity类型的数额有效。这里将数据分为离散数据和聚众数据(cumulativeState of Qatar离散数据:比方身体高度、体重、血压等聚焦数据:比方步数、点火的脂肪量

分别:前边三个是单次取样获取的有效性数据,后面一个是连连取样的到一段时间的增加的多寡

HKStatisticsQuery

HKQuantityType *stepCount = ...NSPredicate *today = ...HKStatisticsOptions sumOptions = HKStaticsOptionCumulativeSum;HKStatisticsQuery *query;query = [HKStatisticsQuery alloc] initWithQuantityType:stepCount quantitySamplePerdicate:today options:sumOptions completionHandler:^(HKStaticsQuery *query, HKStatics *result, NSError *error){ HKQuantity *sum = [result sumQuantity];} 

HKStaticsCollectiion

@interface HKStatisticsCollection:NSObject- (NSArray *)statistics- (HKStatistics *)statisticsForDate:date;- enumberateStatisticsFromDate:startDate toDate:endDate block:(HKStatistics *stats,BOOL *stop))block;@end

</br>

//请求授权- requestAuthorizationToShareTypes:typesToShare readTypes:typesToRead completion:(BOOL success, NSError *error))completion; //监测授权情况 typedef NS_ENUM(NSInteger, HKAuthorizationStatus) { HKAuthorizationStatusNotDetermined = 0, HKAuthorizationStatusSharingDenied, HKAuthorizationStatusSharingAuthorized,}- (HKAuthrizationStatus)authorizationStatusForType: (HKObjectType *)type

</br>

NSFormatter 能支持开采者举办本地化处理

NSnumberFormatterNSDateFormatterNSByteCountFormatterNSMassFormatterNSLengthFormatterNSEnergyFormatter//Code demoNSMassFormatter *formatter = [[NSMassFormatter alloc] init]formatter.forPersonMassUse = YES;HKQuantity * weight = ...double weightKg = [weight doubleValueForUnit:[HKUnit unitFromString:@"kg"]];NSString *localizedString = [formatter stringFromKilograms:weightInKg];

正文从健康应用出发,演讲了Health基特的任何,包罗数据的单位、储存、获取等,最后apple还没开辟者提供了本地化方案。文本是二零一四年WWDC Session 203 的笔记,尤其详实的开始和结果请点击这里(

_readStepLabel.text = [NSString stringWithFormat:@"%.f",stepCount];

});

}];

}

4)读取HealthKit数据

- (void)fetchSumOfSamplesTodayForType:(HKQuantityType *)quantityType unit:(HKUnit *)unit completion:(void (^)(double, NSError *))completionHandler {

NSPredicate *predicate = [self predicateForSamplesToday];

HKStatisticsQuery *query = [[HKStatisticsQuery alloc] initWithQuantityType:quantityType quantitySamplePredicate:predicate options:HKStatisticsOptionCumulativeSum completionHandler:^(HKStatisticsQuery *query, HKStatistics *result, NSError *error) {

HKQuantity *sum = [result sumQuantity];

if (completionHandler) {

double value = [sum doubleValueForUnit:unit];

completionHandler(value, error);

本文由澳门威利斯人发布于威利斯人娱乐,转载请注明出处:iOS修改步数,iOS关于HealthKit使用的主要对象及设

关键词: 澳门威利斯人 日记本 WWDC Introducing HealthKit