您的位置:首页 > 其它

后台处理

2016-04-14 13:29 281 查看
  用户按下主屏幕按钮将调用applicationWillResignActive:,如果谈们稍后将应用切换回前台,将调用applicationDidBecomeActive:。如果用户接听电话,也会发生相同序列的事件。最神奇的是应用启动时也会调用applicationDidBecomeActive:。这两个方法可以用来启动或禁用任何动画、应用内的音频或者其他用于向用户展示的应用内元素。由于使用applicationDidBecomeActive:较多,我们可能在其中添加一些应用初始化代码,而不是在application:didFinishLaunchingWithOptions:中。

  当设备显示收到信息的提醒时,将调用applicationWillResignActive:,应用没有被发送到后台,而是出于不活跃状态,如果此应用是一个游戏或正在进行着视频、音频或动画,那么这是需要暂停他们。点击关闭按钮将调用applicationDidBecomeActive:,点击回复按钮将依次调用applicationDidBecomeActive:、applicationWillResignActive:和applicationDidEnterBackground:三个方法。

  applicationDidEnterBackground:中释放所有可在以后重新创建的资源,保存所用用户数据,关闭网络连接等。如果需要还可以在这里请求在后台运行更长的时间用来保存数据。

  applicationWillEnterForeground:中重新创建在applicationDidEnterBackground:中销毁的内容,比如重新加载用户数据、重新建立网络连接等。

#import "BIDViewController.h"

@interface BIDViewController ()

@property (strong, nonatomic) UILabel * label;
@property (strong, nonatomic) UIImage * smiley;
@property (strong, nonatomic) UIImageView * smileyView;
@property (strong, nonatomic) UISegmentedControl * segmentedControl;

@end

@implementation BIDViewController
{
BOOL animate;
}

- (void)viewDidLoad
{
[super viewDidLoad];

//创建Label
CGRect bounds = self.view.bounds;
CGRect labelFrame = CGRectMake(bounds.origin.x, CGRectGetMidY(bounds) - 50,
bounds.size.width, 100);
self.label = [[UILabel alloc] initWithFrame:labelFrame];
self.label.font = [UIFont fontWithName:@"Helvetica" size:70];
self.label.text = @"Bazinga!";
self.label.textAlignment = NSTextAlignmentCenter;
self.label.backgroundColor = [UIColor clearColor];

// 创建ImageView, smiley.png is 84 x 84
CGRect smileyFrame = CGRectMake(CGRectGetMidX(bounds) - 42,
CGRectGetMidY(bounds)/2 - 42,
84, 84);
self.smileyView = [[UIImageView alloc] initWithFrame:smileyFrame];
self.smileyView.contentMode = UIViewContentModeCenter;
NSString *smileyPath = [[NSBundle mainBundle] pathForResource:@"smiley"
ofType:@"png"];
self.smiley = [UIImage imageWithContentsOfFile:smileyPath];
self.smileyView.image = self.smiley;

//在哪里恢复分段选择的索引并用于配置分段控件,applicationWillEnterForeground方法并不是我们想要的。这个方法被调用的时候应用已经处于运行状态,但设置还是最原始的状态。应该在应用重新运行之后就进行设置,应该在viewDidLoad方法中进行处理。
self.segmentedControl = [[UISegmentedControl alloc] initWithItems:
[NSArray arrayWithObjects:
@"One", @"Two", @"Three", @"Four", nil]] ;
self.segmentedControl.frame = CGRectMake(bounds.origin.x + 20,
50,
bounds.size.width - 40, 30);

[self.view addSubview:self.segmentedControl];
[self.view addSubview:self.smileyView];
[self.view addSubview:self.label];

NSNumber *indexNumber = [[NSUserDefaults standardUserDefaults]
objectForKey:@"selectedIndex"];
if (indexNumber) {
NSInteger selectedIndex = [indexNumber intValue];
self.segmentedControl.selectedSegmentIndex = selectedIndex;
}

NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver:self
selector:@selector(applicationWillResignActive)
name:UIApplicationWillResignActiveNotification
object:nil];
[center addObserver:self
selector:@selector(applicationDidBecomeActive)
name:UIApplicationDidBecomeActiveNotification
object:nil];

[center addObserver:self
selector:@selector(applicationDidEnterBackground)
name:UIApplicationDidEnterBackgroundNotification
object:nil];
[center addObserver:self
selector:@selector(applicationWillEnterForeground)
name:UIApplicationWillEnterForegroundNotification
object:nil];
}

- (void)rotateLabelDown
{
[UIView animateWithDuration:0.5
animations:^{
self.label.transform = CGAffineTransformMakeRotation(M_PI);
}
completion:^(BOOL finished){
[self rotateLabelUp];
}];
}

- (void)rotateLabelUp
{
[UIView animateWithDuration:0.5
animations:^{
self.label.transform = CGAffineTransformMakeRotation(0);
}
completion:^(BOOL finished){
if (animate) {
[self rotateLabelDown];
}
}];
}

- (void)applicationWillResignActive
{
NSLog(@"VC: %@", NSStringFromSelector(_cmd));
animate = NO;
}

- (void)applicationDidBecomeActive
{
NSLog(@"VC: %@", NSStringFromSelector(_cmd));
animate = YES;
[self rotateLabelDown];
}

- (void)applicationDidEnterBackground
{
NSLog(@"VC: %@", NSStringFromSelector(_cmd));
UIApplication *app = [UIApplication sharedApplication];

__block UIBackgroundTaskIdentifier taskId;
taskId = [app beginBackgroundTaskWithExpirationHandler:^{
NSLog(@"Background task ran out of time and was terminated.");
[app endBackgroundTask:taskId];
}];

if (taskId == UIBackgroundTaskInvalid) {
NSLog(@"Failed to start background task!");
return;
}

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
^{
NSLog(@"Starting background task with %f seconds remaining",
app.backgroundTimeRemaining);

self.smiley = nil;
self.smileyView.image = nil;
NSInteger selectedIndex = self.segmentedControl.selectedSegmentIndex;
[[NSUserDefaults standardUserDefaults] setInteger:selectedIndex
forKey:@"selectedIndex"];

// simulate a lengthy (25 seconds) procedure
[NSThread sleepForTimeInterval:25];

NSLog(@"Finishing background task with %f seconds remaining",
app.backgroundTimeRemaining);
[app endBackgroundTask:taskId];
});
}

- (void)applicationWillEnterForeground
{
NSLog(@"VC: %@", NSStringFromSelector(_cmd));
NSString * smileyPath = [[NSBundle mainBundle] pathForResource:@"smiley"
ofType:@"png"];
self.smiley = [UIImage imageWithContentsOfFile:smileyPath];
self.smileyView.image = self.smiley;
}

- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: