6

您好,我正在尝试设置启用了后台交付的健康商店观察者。我的问题是屏幕锁定时它不会提供任何东西。我已经简化了我的代码来解决这个问题:)我的 plist 中有 HealthKit,并且我已经接受了 healthStore 类型的步数。当应用程序打开并且屏幕未锁定时,一切都很好。但是当屏幕被锁定时,我没有得到任何观察。出于测试目的,频率设置为立即。

我的代码如下

- (void)setupHealthStore{
if ([HKHealthStore isHealthDataAvailable])
{
    NSSet *readDataTypes = [self dataTypesToRead];
    self.healthStore = [[HKHealthStore alloc]init];
    [self.healthStore requestAuthorizationToShareTypes:nil readTypes:readDataTypes completion:^(BOOL success, NSError *error)
     {
         if (success)
         {
             HKQuantityType *quantityType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
             [self.healthStore enableBackgroundDeliveryForType:quantityType frequency:HKUpdateFrequencyImmediate withCompletion:^(BOOL success, NSError *error)
             {
                 if (success)
                 {
                     [self setupObserver];
                 }
             }];
         }
     }];
}

}

上述方法在 AppDelegate didfinishLaunchWithOptions 中调用

下一个方法是

- (void)setupObserver{
HKQuantityType *quantityType = [HKObjectType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
HKObserverQuery *query = [[HKObserverQuery alloc]initWithSampleType:quantityType predicate:nil updateHandler:^(HKObserverQuery *query, HKObserverQueryCompletionHandler completionHandler, NSError *error)
{
    if (!error)
    {
        [self alarm];
        if (completionHandler)
        {
            NSLog(@"Completed");
            completionHandler();
        }
    }
    else
    {
        if (completionHandler)
        {
            completionHandler();
        }
    }
}];
[self.healthStore executeQuery:query];

}

当我打开应用程序时,它会立即返回观察结果。

4

4 回答 4

9

当 iPhone 被锁定时,您无法以任何方式访问 healthKit 数据。

当 iPhone 解锁但应用处于后台时,只能使用 HKObserverQuery,用于了解是否添加了一些新样本。

当 iPhone 解锁并且应用程序处于前台时,您可以使用与 HealthKit 框架相关的所有内容。

于 2015-10-14T17:29:26.330 回答
3

我能够让它工作,观察 HealthKit 的体重和血糖变化。

ApplicationDelegate中:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.        

    GlobalHealthManager.startObservingWeightChanges()

    return true
}

HealthManager.swift

    let past = NSDate.distantPast() as NSDate
    let now   = NSDate()
    return HKQuery.predicateForSamplesWithStartDate(past, endDate:now, options: .None)

    }()

    //here is my query:
    lazy var query: HKObserverQuery = {[weak self] in
    let strongSelf = self!
    return HKObserverQuery(sampleType: strongSelf.weightQuantityType,
        //predicate: strongSelf.longRunningPredicate,
        predicate : nil, //all samples delivered
        updateHandler: strongSelf.weightChangedHandler)
    }()




func startObservingWeightChanges(){
        healthKitStore?.executeQuery(query)
        healthKitStore?.enableBackgroundDeliveryForType(weightQuantityType,
            frequency: .Immediate,
            withCompletion: {(succeeded: Bool, error: NSError!) in

            if succeeded{
                println("Enabled background delivery of weight changes")
            } else {
                if let theError = error{
                    print("Failed to enable background delivery of weight changes. ")
                    println("Error = \(theError)")
                }
            }

    })
}



/** this should get called in the background */
func weightChangedHandler(query: HKObserverQuery!,
    completionHandler: HKObserverQueryCompletionHandler!,
    error: NSError!){

        NSLog(" Got an update Here ")

     /** this function will get called each time a new weight sample is added to healthKit.  

    //Here, I need to actually query for the changed values.. 
   //using the standard query functions in HealthKit.. 

         //Tell IOS we're done... updated my server, etc. 
         completionHandler()         
}


}
于 2015-03-02T20:33:32.623 回答
0

步骤的最低更新频率为 1 小时,这意味着您的应用每小时只会被唤醒一次。打开应用程序后,您的观察者查询会立即触发。请参阅 enableBackgroundDeliveryForType 讨论中的注释。

https://developer.apple.com/library/prerelease/ios/documentation/HealthKit/Reference/HKHealthStore_Class/index.html#//apple_ref/occ/instm/HKHealthStore/enableBackgroundDeliveryForType:frequency:withCompletion

于 2015-03-06T20:01:20.527 回答
0

对于 HKObserverQuery,您必须启用应用程序的任何后台模式才能在后台收到 ObserverQuery 的通知(应用程序未终止)。

在此处输入图像描述

于 2015-03-19T13:13:02.023 回答