2012-07-06 73 views
1

我想为一个简单的测试应用程序做两件事。iOS如何使用beginBackgroundTaskWithExpirationHandler执行任务

我被困在努力学习如何使用beginBackgroundTaskWithExpirationHandler

我想执行一个backgroundTask当用户按下主页按钮(没有任何幻想)。在9分钟内,我想提醒用户时间即将到期(如果可能),并允许用户切换回应用程序以更新10分钟。

我不需要与iOS 3向后兼容性,或4

+0

向我们展示你写试试这个什么代码,应用程序将被杀死? – 2012-07-06 14:25:01

+0

它绝对不会在iOS 3上工作,因为它不支持后台进程。另外你为什么要支持iOS 3? – rckoenes 2012-07-06 14:43:35

+1

我说我DON“T想要支持iOS4或iOS3 – 2012-07-06 15:47:19

回答

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; 
} 
+0

没有上述代码去我的应用程序控制器(MainViewController.m)或应用程序委托(AppDelegate.m) – 2012-07-06 17:21:16

+0

把这一切都在视图控制器中有按钮 – 2012-07-06 17:31:35

+0

阿什利,里面的函数“beingBackgroundUpdateTask”你正在调用endBackgroundUpdateTask,并且在函数buttonPressed中,你说要在这两个函数之间执行长时间运行的任务,所以我没有得到它。 – Ranjit 2015-01-27 10:06:44

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];