直接上代码
ViewController.m
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self registLocalNotification];
}
- (void)registLocalNotification
{
UILocalNotification *notification = [[UILocalNotification alloc]init];
notification.fireDate = [NSDate dateWithTimeIntervalSinceNow:10];
notification.alertBody = @"alertBody";
notification.alertLaunchImage = @"icon.png";
//如果通知提醒样式为横幅则alertAction属性无显示 样式为提醒的时候alertAction显示为UIAlertView的右侧按钮
notification.alertAction = @"alertAction";
notification.soundName = UILocalNotificationDefaultSoundName;
notification.timeZone = [NSTimeZone defaultTimeZone];
//0表示不重复,这里可以设置成每天,每小时等等
notification.repeatInterval = 0;
//userInfo用来存储一些信息,比如用于区别其他通知的id等等
notification.userInfo = [NSDictionary dictionaryWithObjectsAndKeys:@"tag", @"id",nil];
notification.applicationIconBadgeNumber = 1;
//生效时间根据fireDate确定
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
//立即生效的通知,与fireDate无关
//[[UIApplication sharedApplication] presentLocalNotificationNow:notification];
//取消通知可以用下面的方法
//[[UIApplication sharedApplication] cancelLocalNotification:notification];
//取消全部到本地通知
//[[UIApplication sharedApplication] cancelAllLocalNotifications];
//通过userInfo来区分不同的通知
/*
for (UILocalNotification *notification in [[UIApplication sharedApplication] scheduledLocalNotifications]) {
NSString *indentiString = [notification.userInfo objectForKey:@"id"];
if ([indentiString isEqualToString:@"tag"] == YES) {
[[UIApplication sharedApplication] cancelLocalNotification:notification];
}
}
*/
}
@end
在appDelegate.m中实现 通过在通知上的操作进入到程序的监听
/**
* 如果接受通知的时候应用程序在前台运行,会触发此方法,不会出现声音,提示等信息
* 如果程序在后台,通过点击通知进入到应用程序也会触发此方法
*
* @param application 当前的应用程序
* @param notification 收到的通知
*/
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
NSLog(@"notification.userInfo=%@",notification.userInfo);
[application setApplicationIconBadgeNumber:0];
}
通知样式的区别
下图通知样式为横幅