概述
苹果公司为了确保IOS设备能在任何时候都能快速响应,保证用户体验,对后台运行的应用程序进行了限制。在IOS4以后,对第三方应用程序开放了后台处理,但在开放后台处理面很谨慎,只对一组用户经常遇到的任务开放。
IOS支持的后台处理主要有四种类型:
1.挂起
暂停执行代码,保留当前状态。用户返回应用程序时看起来一直在运行,实际上为了不让其占系统资源,任务都停止了。
2.本地通知(local notification)
本地通知与推送通知类似,但是由您编写的应用程序生成,这些通知可显示消息,播放声音甚至更新应用程序的徽章数值。
3.任务特定的后台处理
IOS以优雅的方式处理了一些用户需要的特定任务,比如后台继续播放音乐,或者定位,或者VoIP。可在项目的plist文件中的Required Background Modes中添加。
4.长时间运行的任务的任务完成
要使用任务完成,可在应用程序中对任务进行标记,指出该任务结束后才能安全的挂起应用,一般包括文件的上传,下载,大量计算等等。APPLE对这样标记的任务规定有10分钟来完成其操作,一般情况下这都很充足,10分钟后应用将挂起。
实现本地通知和任务完成的Demo
点击Alert Me 实现即使在关闭应用的情况下,过30秒进行本地通知
点击BackgroundCount 实现挂起的后台处理
两个任务完成时都有声音提醒
准备工作
#import <UIKit/UIKit.h>
//播放系统声音的框架
#import <AudioToolbox/AudioToolbox.h>
@interface ViewController : UIViewController
@property (weak, nonatomic) IBOutlet UILabel *countLabel;
- (IBAction)doCount:(id)sender;
- (IBAction)doAlert:(id)sender;
@end.m文件中声明实例
@interface ViewController ()
{
int _count;
NSTimer *_timer;
UIBackgroundTaskIdentifier _task;
SystemSoundID _soundID;
UILocalNotification *_localNotification;
}初始化
- (void)viewDidLoad
{
[super viewDidLoad];
_count = 0;
NSString *soundPath = [[NSBundle mainBundle] pathForResource:@"alertsound" ofType:@"wav"];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:soundPath], &_soundID);
_localNotification = [[UILocalNotification alloc] init];
}实现本地通知
- (IBAction)doAlert:(id)sender {
//取消其他本地通知
[[UIApplication sharedApplication] cancelAllLocalNotifications];
//设置属性,徽章数字,通知时间,时区,声音,间隔,内容等
_localNotification.applicationIconBadgeNumber = 1;
_localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:30];
_localNotification.timeZone = [NSTimeZone defaultTimeZone];
_localNotification.soundName = @"alertsound.wav";
_localNotification.repeatInterval = NSDayCalendarUnit;
_localNotification.alertBody = @"我是横幅提醒!";
[[UIApplication sharedApplication] scheduleLocalNotification:_localNotification];
}通知时效果
当然也可以在每次进入前台的时候把徽章数字清零
- (void)applicationDidBecomeActive:(UIApplication *)application
{
[UIApplication sharedApplication].applicationIconBadgeNumber = 0;
}实现后台任务完成
- (IBAction)doCount:(id)sender {
_task = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
}];
//对计时器参数设置,调用countUp方法
_timer = [NSTimer scheduledTimerWithTimeInterval:0.1
target:self
selector:@selector(countUp)
userInfo:nil
repeats:YES];
}
//计数到100时停止结束,播放声音提醒。
- (void)countUp
{
if (_count == 100) {
AudioServicesPlaySystemSound(_soundID);
[_timer invalidate];
_timer = nil;
[[UIApplication sharedApplication] endBackgroundTask:_task];
} else {
_count++;
self.countLabel.text = [NSString stringWithFormat:@"%d", _count];
}
}
开始计数了,应用退到后台,很快就有声音提示 计数完成
本文详细介绍了iOS中如何实现本地通知以及进行任务特定的后台处理,包括挂起操作、本地通知的设置和发送,以及如何确保长时间运行的任务能够顺利完成。通过一个Demo展示具体实现过程,帮助开发者掌握相关技能。
1643

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



