UILocalNotification *localNotification = [[UILocalNotification alloc]init];
// 接收到通知时,播放的音频文件
localNotification.soundName = @"shake.wav";
// 通知的发送时间
localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:5];
// 最好带上时区,用于对fireDate的补充
localNotification.timeZone = [NSTimeZone defaultTimeZone];
// 通知的内容
localNotification.alertBody = @"通知的内容";
// 锁屏界面显示的通知内容,灰色小字
localNotification.alertAction = @"通知的内容2(在锁屏界面)";
// 点击通知,打开应用时,加载的启动图片,只能是是应用的启动图片
localNotification.alertLaunchImage = @"Default";
// 接收到通知后,图标右上角显示的数字
localNotification.applicationIconBadgeNumber = 20;
// 通知的附加信息,字典类型
localNotification.userInfo = @{
@"dictKey":@"userInfo详情",
@"dictKey2":@"userInfo详情2"
};
// 启用通知,按照上文的设置,上文设置的时5秒后发送通知,那就是代码执行到此行,再过5秒才会发送通知
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
// 立即发送通知,也就是说上文的fireDate和timeZone就没有作用了.
// 下面代码存在的意义就是当程序在后台运行时,立即发送通知
// [[UIApplication sharedApplication] presentLocalNotificationNow:localNotification];
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions;
如果程序是在前台,方法会回调,不会有横幅提示;
/*
如果希望程序在前台时,不提示用户,可以加程序运行状态的判断 application.applicationState == UIApplicationStateActive),
程序由后台到前台时的状态变化是下面这样的, 如果是前台到后台则反过来:
UIApplicationStateBackground(后台) -> UIApplicationStateInactive(未激活,此时所有UI界面无法接收用户点击) -> UIApplicationStateActive(激活)
*/
如果程序是在后台,方法会回调,有横幅提示.
1 - (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification 2 { 3 if (application.applicationState == UIApplicationStateActive) return; 4 self.label.text = @"收到通知时,程序还活着(前台\后台都算),就会回调本方法"; 5 }
因此在处理通知时,需要判断程序到底是 点击应用图标启动的,还是 点击横幅通知启动的
1 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 2 { 3 UILocalNotification *note = launchOptions[UIApplicationLaunchOptionsLocalNotificationKey]; 4 5 if (note) { 6 self.label.text = @"点击横幅通知启动的程序"; 7 }else{ 8 self.label.text = @"点击app图标启动的程序"; 9 } 10 11 return YES; 12 }