为了账号安全,请及时绑定邮箱和手机立即绑定

应用未运行时的Healthkit后台传递

应用未运行时的Healthkit后台传递

白猪掌柜的 2019-11-28 13:46:33
如果HealthKit后台交付未运行,是否可以启动该应用程序?特别是在终止状态下?
查看完整描述

3 回答

?
凤凰求蛊

TA贡献1825条经验 获得超4个赞

在iOS 8.1中可以。不过,您需要确保在应用程序委托的中重新创建观察者查询application:didFinishLaunchingWithOptions:。8.0中的错误完全阻止了HealthKit的后台通知。


编辑:


在您的AppDelegate中:


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    //create/get your HKHealthStore instance (called healthStore here)

    //get permission to read the data types you need.

    //define type, frequency, and predicate (called type, frequency, and predicate here, appropriately)


    UIBackgroundTaskIdentifier __block taskID = [application beginBackgroundTaskWithExpirationHandler:^{

        if (taskID != UIBackgroundTaskInvalid) {

            [application endBackgroundTask:taskID];

            taskID = UIBackgroundTaskInvalid;

        }

    }];

    [healthStore enableBackgroundDeliveryForType:type frequency:frequency withCompletion:^(BOOL success, NSError *error) {}];

    HKQuery *query = [[HKObserverQuery alloc] initWithSampleType:healthType predicate:predicate updateHandler:

        ^void(HKObserverQuery *query, HKObserverQueryCompletionHandler completionHandler, NSError *error)

        {

            //If we don't call the completion handler right away, Apple gets mad. They'll try sending us the same notification here 3 times on a back-off algorithm.  The preferred method is we just call the completion handler.  Makes me wonder why they even HAVE a completionHandler if we're expected to just call it right away...

            if (completionHandler) {

                completionHandler();

            }

            //HANDLE DATA HERE

            if (taskID != UIBackgroundTaskInvalid) {

                [application endBackgroundTask:taskID];

                taskID = UIBackgroundTaskInvalid;

            }

        }];

    [healthStore executeQuery:query];

}


查看完整回答
反对 回复 2019-11-28
  • 3 回答
  • 0 关注
  • 856 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信