最近正在搞IOS的本地通知UILocalNotification。遇到了一些问题,也查了不少资料,果断整理一下。
首先先copy一段话:本地通知,local notification,用于基于时间行为的通知,比如有关日历或者todo列表的小应用。另外,应用如果在后台执行,iOS允许它在受限的时间内运行,它也会发现本地通知有用。比如,一个应用,在后台运行,向应用的服务器端获取消息,当消息到达时,比如下载更新版本的提示消息,通过本地通知机制通知用户。
其实要用着个本地通知也不算难,我们一步一步来:
1.初始化 UILocalNotification
UILocalNotification *newNotification = [[UILocalNotification alloc] init];
2.配置UILocalNotifycation的一些属性
if (newNotification) {
//触发时间
newNotification.fireDate = _datePiker.date ;
//通知正文
newNotification.alertBody = _clockEntity.strTag;
//通知的背景声音
newNotification.soundName = [NSString stringWithFormat: @"%@.caf",_clockEntity.strRing];
//通知行为
newNotification.alertAction = @"查看闹钟";
//通知重复间隔,这里的表示每分钟发一条,还可以定义为每小时,每天,每月,每年等等
newNotification.repeatInterval = kCFCalendarUnitMinute;
//这里可以配置一些额外信息
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:clockID] forKey:@"ActivityClock"];
newNotification.userInfo = userInfo;
}
上面的alertBody是设备收到本地通知时横额或锁屏时的主要文字内容,alertActions是锁屏时显示的slide to后面的文字内容
3.展示通知
* - (void)scheduleLocalNotification:(UILocalNotification *)notification:根据触发时间的配置展示通知消息,
* - (void)presentLocalNotificationNow:(UILocalNotification *)notification:立即发送通知到本机
[[UIApplication sharedApplication] scheduleLocalNotification:newNotification];
3.处理通知这里就要分两种情况了
一.你的程序运行在后台
二.你的程序运行在前台
好吧 其实它们的处理都是调用了AppDelegate中的
-(void) application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification 方法。不过如果是运行在前台,则直接调用该方法,如果是运行在后台,则会有弹窗提示用户,用户点击弹窗 进入程序才调用该方法.
那就有些郁闷了。你在前台后台都调用这个方法,我怎么判断啊。还能做朋友吗。。。
这时候,我们其实是可以判断Application的状态,如果状态是活跃的花,说明就在前台咯。
在didReceiveLocalNotification方法中添加
UIApplicationState state = application.applicationState;
if (state == UIApplicationStateActive) {
//前台
}else if (state == UIApplicationStateInactive)
//后台
}