iOS7 Programming Cookbook 第十六章学习笔记

####Completing a Long-Running Task in the Background

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88

#import "AppDelegate.h"

@interface AppDelegate ()
//UIBackgroundTaskIdentifier : 一个独特的标志,这个标志标识请求在后台运行
@property (nonatomic, unsafe_unretained) UIBackgroundTaskIdentifier backgroundTaskIdentifier;
@property (nonatomic, strong) NSTimer *myTimer;

@end

@implementation AppDelegate

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

self.window = [[UIWindow alloc] initWithFrame:
[[UIScreen mainScreen] bounds]];

self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}

//结束后台任务
- (void)endBackgroundTask{
dispatch_queue_t mainQueue = dispatch_get_main_queue();
__weak AppDelegate *weakSelf = self;
dispatch_async(mainQueue, ^(void) {
AppDelegate *strongSelf = weakSelf;
if (strongSelf != nil){
//时间停止计时
[strongSelf.myTimer invalidate];
[[UIApplication sharedApplication] endBackgroundTask:self.backgroundTaskIdentifier];
//这个常数应该用于初始化变量或检查错误。
strongSelf.backgroundTaskIdentifier = UIBackgroundTaskInvalid;
}

});

}

//一个布尔值表示是否支持多任务当前的设备上。(只读)
- (BOOL)isMultitaskingSupported{
BOOL result = NO;
if ([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)]){
result = [[UIDevice currentDevice] isMultitaskingSupported];
}
return result;

}

- (void)timerMethod:(NSTimer *)paramSender{

NSTimeInterval backgroundTimeRemaining =
[[UIApplication sharedApplication] backgroundTimeRemaining];

if (backgroundTimeRemaining == DBL_MAX){
NSLog(@"背景剩余时间=待定");
} else {
NSLog(@"Background Time Remaining = %.02f Seconds",
backgroundTimeRemaining);
}

}

//应用程序已经在后台
- (void)applicationDidEnterBackground:(UIApplication *)application{

if ([self isMultitaskingSupported] == NO){
return;
}
//添加方法
self.myTimer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(timerMethod:) userInfo:nil repeats:YES];
//标志着一个新的开始长时间运行的后台任务。
self.backgroundTaskIdentifier = [application beginBackgroundTaskWithExpirationHandler:^(void) {
[self endBackgroundTask];
}];

}

//应用程序即将进入前景
- (void)applicationWillEnterForeground:(UIApplication *)application{
if (self.backgroundTaskIdentifier != UIBackgroundTaskInvalid){
[self endBackgroundTask];
}

}

@end

Reference

坚持原创技术分享,您的支持将鼓励我继续创作!
0%