在现阶的APP中关于消息的处理需求越来越大,系统需要将一下消息以音频或者文字的形式提示用户,这里便用到推送,推送消息主要有本地和远程推送,今天我们先研究一下简单的本地通知,下面以闹钟为例子。
1、我们首先要注册通知
UIApplication * application=[UIApplication sharedApplication];
//如果当前应用程序没有注册本地通知,需要注册
if([application currentUserNotificationSettings].types==UIUserNotificationTypeNone){
//设置提示支持的提示方式
// UIUserNotificationTypeBadge 提示图标
// UIUserNotificationTypeSound 提示声音
// UIUserNotificationTypeAlert 提示弹框
UIUserNotificationSettings * setting=[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert categories:nil];
[application registerUserNotificationSettings:setting];
}
//删除之前的重复通知
[application cancelAllLocalNotifications];通知注册完成之后可以在设置里面进行查看,同时也可以删除。如图:


2、设置通知
#pragma mark - 添加本地通知
- (void) _addLocalNotification:(NSDate *) date{
UILocalNotification * noti=[[UILocalNotification alloc] init];
//设置开始时间
noti.fireDate=date;
//设置body
noti.alertBody=@"该起床了";
//设置action
noti.alertAction=@"解锁";
//设置闹铃
noti.soundName=@"4195.mp3";
#warning 注册完之后如果不删除,下次会继续存在,即使从模拟器卸载掉也会保留
//注册通知
[[UIApplication sharedApplication] scheduleLocalNotification:noti];
}
这样就会在设置的时间内闹钟响起来,如图:

3、这样闹钟的功能基本实现,但是还有一个问题,因为如果当前程序是打开的会导致闹钟不会响起来,那我们如何解决问题呢。此时我们需要借助播放器来解决
@interface AppDelegate ()
{
//定义播放器播放音乐
AVAudioPlayer * player;
//用来判断是不是从通知窗口打开
BOOL isFromNotification;
}
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{
//如果是从通知窗口进来的则不需要播放音频
if (isFromNotification) {
return;
}
//初始化音乐播放音乐
NSURL * url=[[NSBundle mainBundle] URLForResource:@"4195.mp3" withExtension:nil];
player=[[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
player.numberOfLoops=0;
[player prepareToPlay];
[player play];
}
这样便大功告成了。
想要了解更多内容的小伙伴,可以点击查看源码,亲自运行测试。
疑问咨询或技术交流,请加入官方QQ群:
(452379712)
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文:http://blog.csdn.net/jerehedu/article/details/47727139