如果我们想让程序在后台长期运行可以使用block来实现,下面列出实现代码。
声明 UIBackgroundTaskIdentifier 对象
#import "AppDelegate.h"
@interface AppDelegate ()
@property (assign , nonatomic) UIBackgroundTaskIdentifier backgroundUpdateTask;
@end- (void)applicationDidEnterBackground:(UIApplication *)application {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
[self beingBackgroundUpdateTask];
}
- (void) beingBackgroundUpdateTask
{
// 需要长期运行的代码
for (long i = 0; i < 100000000000; i++) {
NSLog(@"%ld ....................",i);
}
self.backgroundUpdateTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
[self endBackgroundUpdateTask];
}];
}
- (void) endBackgroundUpdateTask
{
[[UIApplication sharedApplication] endBackgroundTask:self.backgroundUpdateTask];
self.backgroundUpdateTask = UIBackgroundTaskInvalid;
}
本文介绍了使用block技术使iOS应用在后台长期运行的方法,并提供了相关的实现代码,重点关注BackgroundTaskIdentifier的使用。
1万+

被折叠的 条评论
为什么被折叠?



