在现阶的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];
}
这样便大功告成了。