简体   繁体   English

Healthkit:数据未显示首次运行。

[英]Healthkit: Data not showing first time running.

I have a strange problem when reading data out of healthkit. 从Healthkit读取数据时遇到一个奇怪的问题。 The first time when i press the button the weight is printed 0, the next times i press the button the weight is printed as normal.I would really appreciate it if someone could help me. 第一次按下按钮时砝码打印为0,下次按下按钮时砝码将正常打印。如果有人可以帮助我,我将非常感激。 Thanks! 谢谢!

I have the following code. 我有以下代码。

HealtkitManager.h HealtkitManager.h

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import <HealthKit/HealthKit.h>

@interface HealthKitManager : NSObject
@property (nonatomic) float weight;
@property (nonatomic) HKHealthStore *healthStore;

+(HealthKitManager *)sharedManager;

-(void) requestAuthorization;
-(double) readWeight;




@end

Healthkitmanager.m Healthkitmanager.m

#import "HealthKitManager.h"
#import <healthKit/healthKit.h>
#import "StartScreen.h"
@interface HealthKitManager ()

@end



@implementation HealthKitManager

+(HealthKitManager *) sharedManager{
    static dispatch_once_t pred = 0;
    static HealthKitManager *instance = nil;
    dispatch_once(&pred, ^{
        instance = [[HealthKitManager alloc]init];
        instance.healthStore = [[HKHealthStore alloc]init];
    });
    return instance;
}

-(void)requestAuthorization {
    if([HKHealthStore isHealthDataAvailable]==NO){
        return;
    }

    NSArray *readTypes = @[[HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyMass],
                           [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyMassIndex],
                           [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyFatPercentage]];

    [self.healthStore requestAuthorizationToShareTypes:nil readTypes:[NSSet setWithArray:readTypes] completion:nil];

}

-(double) readWeight{
    NSMassFormatter *massFormatter = [[NSMassFormatter alloc]init];
    massFormatter.unitStyle = NSFormattingUnitStyleLong;

    HKQuantityType *weightType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierBodyMass];

    [self fetchMostRecentDataOfQuantityType:weightType withCompletion:^(HKQuantity *mostRecentQuantity, NSError *error) {
        if(!mostRecentQuantity){
            NSLog(@"%@",@"Error. ");
        }
        else{
            HKUnit *weightUnit = [HKUnit gramUnit];
            _weight = [mostRecentQuantity doubleValueForUnit:weightUnit];
            _weight = (float)_weight/1000.00f;
        }
    }];
    return _weight;
}

- (void)fetchMostRecentDataOfQuantityType:(HKQuantityType *)quantityType withCompletion:(void (^)(HKQuantity *mostRecentQuantity, NSError *error))completion {
    NSSortDescriptor *timeSortDescriptor = [[NSSortDescriptor alloc] initWithKey:HKSampleSortIdentifierEndDate ascending:NO];


    HKSampleQuery *query = [[HKSampleQuery alloc] initWithSampleType:quantityType predicate:nil limit:1 sortDescriptors:@[timeSortDescriptor] resultsHandler:^(HKSampleQuery *query, NSArray *results, NSError *error) {
        if (!results) {
            if (completion) {
                completion(nil, error);
            }

            return;
        }

        if (completion) {

            HKQuantitySample *quantitySample = results.firstObject;
            HKQuantity *quantity = quantitySample.quantity;

            completion(quantity, error);
        }
    }];

    [self.healthStore executeQuery:query];
}


@end

Startscreen.m 开始画面

#import "StartScreen.h"
#import "HealthKitManager.h"

@interface StartScreen ()
@property(nonatomic,weak) IBOutlet UILabel *weightLabel;

@end

@implementation StartScreen

- (void)viewDidLoad {
    [super viewDidLoad];
    [[HealthKitManager sharedManager] requestAuthorization];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


-(IBAction)readAgeButtonPressed:(id)sender{
    HealthKitManager *readWeight = [[HealthKitManager sharedManager] init];
   NSLog(@"%.2f",readWeight.readWeight);

}
@end

You use singleton HealthKitManager but your code 您使用单例HealthKitManager,但是您的代码

HealthKitManager *readWeight = [[HealthKitManager sharedManager] init];

in IBAction readAgeButtonPressed should be 在IBAction中,readAgeButtonPressed应该是

HealthKitManager *readWeight = [HealthKitManager sharedManager];

You don't need init . 您不需要init

Also, you can change the code 另外,您可以更改代码

[[HealthKitManager sharedManager] requestAuthorization];

to be 成为

HealthKitManager *readWeight = [HealthKitManager sharedManager];
[readWeight requestAuthorization];
NSLog(@"%.2f",readWeight.readWeight);

checking the value of readWeight. 检查readWeight的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM