1

我正在尝试为一个简单的测试应用程序做两件事。

我一直在尝试学习如何使用 beginBackgroundTaskWithExpirationHandler

我想在用户按下主页按钮时执行一个 backgroundTask(没什么花哨的)。9 分钟后,我想提醒用户时间即将到期(如果可能)并允许用户切换回应用程序以续订 10 分钟。

我不需要向后兼容 iOS 3 或 4。

4

2 回答 2

3

如果您希望代码在后台继续运行,则需要将其包装在后台任务中。完成后打电话也很重要endBackgroundTask- 否则应用程序将在分配的时间到期后被杀死

- (IBAction) buttonPressed: (id) sender

        [self beingBackgroundUpdateTask];

        // Do your long running background thing here

        [self endBackgroundUpdateTask];
    });
}
- (void) beingBackgroundUpdateTask
{
    self.backgroundUpdateTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        [self endBackgroundUpdateTask];
    }];
}

- (void) endBackgroundUpdateTask
{
    [[UIApplication sharedApplication] endBackgroundTask: self.backgroundUpdateTask];
    self.backgroundUpdateTask = UIBackgroundTaskInvalid;
}
于 2012-07-06T14:39:15.827 回答
1

将代码放在applicationDidEnterBackground你的函数中UIApplicationDelegate。您将需要设置UILocalNotification并安排它。您还应该禁用它,applicationWillEnterForeground这样它就不会触发用户在过期之前返回应用程序。

- (void)applicationDidEnterBackground:(UIApplication *)application
{
  UILocalNotification *timerNotification = [[UILocalNotification alloc] init];
  //set up notification with proper time and attributes
  [[UIApplication sharedApplication] scheduleLocalNotification:timerNotification];
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
  [[UIApplication sharedApplication] cancelAllLocalNotifications];
}

我在那里提供的取消代码实际上会取消所有通知。如果您有多个通知并且只想取消一个特定的通知,则应在userInfo设置通知的属性时为其提供键/值。然后,当应用程序进入前台时,通过执行获取所有活动通知的列表

NSArray *notifications = [[UIApplication sharedApplication] scheduledLocalNotifications];

并遍历它们,检查userInfo直到你到达你想要的那个,然后取消那个

[[UIApplication sharedApplication] cancelLocalNotification:whateverNotification];

于 2012-07-06T14:34:17.797 回答