我正在尝试为一个简单的测试应用程序做两件事。
我一直在尝试学习如何使用 beginBackgroundTaskWithExpirationHandler
我想在用户按下主页按钮时执行一个 backgroundTask(没什么花哨的)。9 分钟后,我想提醒用户时间即将到期(如果可能)并允许用户切换回应用程序以续订 10 分钟。
我不需要向后兼容 iOS 3 或 4。
我正在尝试为一个简单的测试应用程序做两件事。
我一直在尝试学习如何使用 beginBackgroundTaskWithExpirationHandler
我想在用户按下主页按钮时执行一个 backgroundTask(没什么花哨的)。9 分钟后,我想提醒用户时间即将到期(如果可能)并允许用户切换回应用程序以续订 10 分钟。
我不需要向后兼容 iOS 3 或 4。
如果您希望代码在后台继续运行,则需要将其包装在后台任务中。完成后打电话也很重要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;
}
将代码放在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];