屏幕锁定时,HealthStore enableBackgroundDelivery

Tho*_*mas 5 objective-c background-process ios healthkit hkhealthstore

您好我正在尝试设置启用了后台传递的运行状况存储观察器.我的问题是,当屏幕被锁定时,它不会传递任何东西.我已经简化了我的代码来解决这个问题:)我在我的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];
                 }
             }];
         }
     }];
}
Run Code Online (Sandbox Code Playgroud)

}

在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];
Run Code Online (Sandbox Code Playgroud)

}

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

jeo*_*cha 8

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

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

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


小智 3

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

应用程序委托中:

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

    GlobalHealthManager.startObservingWeightChanges()

    return true
}
Run Code Online (Sandbox Code Playgroud)

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()         
}


}
Run Code Online (Sandbox Code Playgroud)