iOS 后台处理
iOS 后台处理的常见用途
1、进入后台时候删除资源:应用处于挂起状态的时候所占用的资源越少,该应用被iOS终止的风险就越低。通过从内存中清理那些易于重新创建的资源,可以增加应用驻留内存的机会,因此可以大幅加快重启速度。
2、进入后台时候保存状态:保存与用户执行的操作相关的所有信息,这样的话,用户下次回来的时候,依然可以恢复到他们离开时的进度。
3、延时执行,请求更多的后台时间:如果进入后台花费了很多时间,应用可能会从内存中移除,如果应用正在进行文件传输,没有能够完成的话,将会带来很多不便。我们可以将applicationDidEnterBackground 作为平台,告诉系统,你还有额外的工作要做,然后启动一个程序块,真正的执行该工作。
例解:
@property (strong, nonatomic) UILabel *label;
@property (strong, nonatomic) UIImage *smiley;
@property (strong, nonatomic) UIImageView *smileyView;
@property (strong, nonatomic) UISegmentedControl *segmentedControl;
@implementation BIDViewController {
BOOL animate;
}
- (void)viewDidLoad
{
[super viewDidLoad]; CGRect bounds = self.view.bounds;
CGRect labelFrame = CGRectMake(bounds.origin.x, CGRectGetMidY(bounds) - ,
bounds.size.width, ); //转动的Label
self.label = [[UILabel alloc] initWithFrame:labelFrame];
self.label.font = [UIFont fontWithName:@"Helvetica" size:];
self.label.text = @"Bazinga!";
self.label.textAlignment = NSTextAlignmentCenter;
self.label.backgroundColor = [UIColor clearColor]; //笑脸
CGRect smileyFrame = CGRectMake(CGRectGetMidX(bounds) - ,
CGRectGetMidY(bounds)/ - ,
, );
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; //分段器
self.segmentedControl = [[UISegmentedControl alloc] initWithItems:
[NSArray arrayWithObjects:
@"One", @"Two", @"Three", @"Four", nil]] ;
self.segmentedControl.frame = CGRectMake(bounds.origin.x + ,
,
bounds.size.width - , ); [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];
}
//Label 向下转动
- (void)rotateLabelDown
{
[UIView animateWithDuration:0.5
animations:^{
self.label.transform = CGAffineTransformMakeRotation(M_PI);
}
completion:^(BOOL finished){
[self rotateLabelUp];
}];
} //Label 向上转动
- (void)rotateLabelUp
{
[UIView animateWithDuration:0.5
animations:^{
self.label.transform = CGAffineTransformMakeRotation();
}
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 实例。
UIApplication *app = [UIApplication sharedApplication]; //声明了taskId变量、并用__block修饰。
__block UIBackgroundTaskIdentifier taskId; //告诉系统,需要更多的时间来完成某件事,并承诺在完成之后告诉它。如果系统判定我们运行了太久时间并决定停止运行,可以调用我们做为参数提供的程序块
taskId = [app beginBackgroundTaskWithExpirationHandler:^{
NSLog(@"Background task ran out of time and was terminated.");
[app endBackgroundTask:taskId];
}]; //如果系统返回的值是UIBackgroundTaskInvalid,表明系统没有为我们提供任何多余的时间。
if (taskId == UIBackgroundTaskInvalid) {
NSLog(@"Failed to start background task!");
return;
} //
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, ),
^{
NSLog(@"Starting background task with %f seconds remaining",
app.backgroundTimeRemaining); self.smiley = nil;
self.smileyView.image = nil; //存储segmentedControl的位置
NSInteger selectedIndex = self.segmentedControl.selectedSegmentIndex;
[[NSUserDefaults standardUserDefaults] setInteger:selectedIndex
forKey:@"selectedIndex"]; //模拟一个25秒的过程
[NSThread sleepForTimeInterval:]; 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;
}
运行效果:

iOS 后台处理的更多相关文章
- iOS后台定位实现
iOS后台定位实现 (2013-01-24 16:43:12) 工作中碰到一个定位的应用场景:app需要在后台运行,实时上传用户地理位置. 苹果对iOS的规范性在提升了app的品质的同时也 ...
- iOS 后台运行 类型
iOS后台运行,需要有特定的类型才可以进行.这些内容并不是一直不变的,苹果也在逐步的更新这些内容. 本文内容是2015年11月03日时苹果支持的后台运行类型. 这是官方连接地址 其中较为重要的是下面这 ...
- iOS后台运行
http://www.cocoachina.com/bbs/read.php?tid=149564 文一 我从苹果文档中得知,一般的应用在进入后台的时候可以获取一定时间来运行相关任务,也就是说可以在后 ...
- IOS 后台执行
在IOS后台执行是本文要介绍的内容,大多数应用程序进入后台状态不久后转入暂停状态.在这种状态下,应用程序不执行任何代码,并有可能在任意时候从内存中删除.应用程序提供特定的服务,用户可以请求后台执行时间 ...
- iOS 后台运行实现 --备用
文一 我从苹果文档中得知,一般的应用在进入后台的时候可以获取一定时间来运行相关任务,也就是说可以在后台运行一小段时间. 还有三种类型的可以运行在后以,1.音乐2.location 3.voip 文二 ...
- iOS 后台定位被拒注意事项
iOS 后台定位被拒的原因很简单就是没有达到苹果对后台定位的要求. 本地要求: 1.在plist文件中添加字段 "Privacy - Location Always Usage Descri ...
- iOS 后台持续定位详解(支持ISO9.0以上)
iOS 后台持续定位详解(支持ISO9.0以上) #import <CoreLocation/CoreLocation.h>并实现CLLocationManagerDelegate 代理, ...
- IOS后台执行
大多数应用程序进入后台状态不久后转入暂停状态.在这种状态下,应用程序不执行任何代码,并有可能在任意时候从内存中删除.应用程序提供特定的服务,用户可以请求后台执行时间,以提供这些服务. 判断是否支持多线 ...
- iOS后台解析
iOS后台 上个月给小妹买了一台6s 她问我双击 Home 键之后 弹出的那些应用会不会耗电 我找到一篇文章 正好说的就是这个问题 摘要翻译一下 原文地址 http://www.speirs.org/ ...
随机推荐
- jQuery实践-网页版2048小游戏
▓▓▓▓▓▓ 大致介绍 看了一个实现网页版2048小游戏的视频,觉得能做出自己以前喜欢玩的小游戏很有意思便自己动手试了试,真正的验证了这句话-不要以为你以为的就是你以为的,看视频时觉得看懂了,会写了, ...
- 前端网络、JavaScript优化以及开发小技巧
一.网络优化 YSlow有23条规则,中文可以参考这里.这几十条规则最主要是在做消除或减少不必要的网络延迟,将需要传输的数据压缩至最少. 1)合并压缩CSS.JavaScript.图片,静态资源CDN ...
- 编写高质量代码:改善Java程序的151个建议(第5章:数组和集合___建议75~78)
建议75:集合中的元素必须做到compareTo和equals同步 实现了Comparable接口的元素就可以排序,compareTo方法是Comparable接口要求必须实现的,它与equals方法 ...
- 看完SQL Server 2014 Q/A答疑集锦:想不升级都难!
看完SQL Server 2014 Q/A答疑集锦:想不升级都难! 转载自:http://mp.weixin.qq.com/s/5rZCgnMKmJqeC7hbe4CZ_g 本期嘉宾为微软技术中心技术 ...
- 使用ServiceStack构建Web服务
提到构建WebService服务,大家肯定第一个想到的是使用WCF,因为简单快捷嘛.首先要说明的是,本人对WCF不太了解,但是想快速建立一个WebService,于是看到了MSDN上的这一篇文章 Bu ...
- 【翻译】MongoDB指南/CRUD操作(四)
[原文地址]https://docs.mongodb.com/manual/ CRUD操作(四) 1 查询方案(Query Plans) MongoDB 查询优化程序处理查询并且针对给定可利用的索引选 ...
- fiddler发送post请求
1.指定为 post 请求,输入 url Content-Type: application/x-www-form-urlencoded;charset=utf-8 request body中的参数格 ...
- .NET Core的文件系统[5]:扩展文件系统构建一个简易版“云盘”
FileProvider构建了一个抽象文件系统,作为它的两个具体实现,PhysicalFileProvider和EmbeddedFileProvider则分别为我们构建了一个物理文件系统和程序集内嵌文 ...
- [.NET] 打造一个很简单的文档转换器 - 使用组件 Spire.Office
打造一个很简单的文档转换器 - 使用组件 Spire.Office [博主]反骨仔 [原文]http://www.cnblogs.com/liqingwen/p/6024827.html 序 之前,& ...
- LINQ to SQL Where条件
1. 适用场景 实现条件的过滤和查询等功能. 2. 说明 跟SQL语句中的where作用相似,都起到了范围的限定即过滤的作用,而判断条件是紧跟后面的条件子句.where主要分为三种形式:简单形式.条件 ...