UILocalNotification 本地通知
github URL: https://github.com/LiuRuian/ReferenceCode
// 1.创建初始化本地通知
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
// 2.设置属性
// 2.0 设置启动图片
localNotification.alertLaunchImage = @"Default";
// 2.1 设置标题, 锁屏状态下显示的下面小标题的滑动来 显示的文字
localNotification.alertAction = @"友情提示,这是本地通知的标题";
// 2.2 设置通知内容
localNotification.alertBody = @"这里是本地通知的内容";
// 2.3 设置通知提示的红色气泡数字
localNotification.applicationIconBadgeNumber = 1;
// 2.4 设置通知的时间
localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:6];
//2.5 设置循环次数0表示不重复
//localNotification.repeatInterval = kCFCalendarUnitMinute;
// 2.6 设置声音,可以换成其他铃声 alarm.soundName = @"myMusic.caf"
localNotification.soundName= UILocalNotificationDefaultSoundName;
// 2.7 设置本地时区
localNotification.timeZone=[NSTimeZone defaultTimeZone];
// 2.8 设置通知的额外信息
localNotification.userInfo = @{@"icon":@"icon.png",@"title":@"news",@"time":@"2014"};
//3. 添加本地通知
UIApplication *app = [UIApplication sharedApplication];
// 取消现在的通知
[app cancelLocalNotification:localNotification];
// 取消所有已有的通知
[app cancelAllLocalNotifications];
// 加入新的通知
[app scheduleLocalNotification:localNotification];
// 当App再后台运行时,可调用此方法可以立即发出通知
[app presentLocalNotificationNow:localNotification];
补充
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// 获取是否有通知
UILocalNotification *localNotification = launchOptions[UIApplicationLaunchOptionsLocalNotificationKey];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 70, 200, 40)];
label.backgroundColor = [UIColor redColor];
if (localNotification) {
label.text = @"通知进入程序";
ViewController *vc = self.window.rootViewController.childViewControllers.firstObject;
[vc performSegueWithIdentifier:@"pushToDetailVC" sender:localNotification];
}else
{
label.text = @"点击图标进入程序";
}
self.label = label;
[[[self.window.rootViewController.childViewControllers firstObject] view] addSubview:label];
return YES;
}
// 收到本地通知时调用
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
/*applicationState 应用的几种状态
UIApplicationStateActive,
UIApplicationStateInactive,
UIApplicationStateBackground
*/
if (application.applicationState != UIApplicationStateActive)
{
ViewController *vc = self.window.rootViewController.childViewControllers.firstObject;
// 执行 Identifier=pushToDetailVC 的segue
[vc performSegueWithIdentifier:@"pushToDetailVC" sender:notification];
}
self.label.text = @"点击通知进入前台";
}
ViewController.m
// segue 传入数据UILocalNotification 数据
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(UILocalNotification *)note
{
// 跳转的时候传值
DetailViewController *detailVC = segue.destinationViewController;
detailVC.localNotification = note;
}