注:按Home键让App进入后台执行时。方可查看通知。
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
// 注冊本地通知
UILocalNotification *localnotifit = [[UILocalNotification alloc] init];
if (localnotifit) {
// 获取通知时间
NSDate *now = [NSDate date];
localnotifit.timeZone = [NSTimeZone defaultTimeZone];
// 10秒后開始通知
localnotifit.fireDate = [now dateByAddingTimeInterval:10.0];
// 反复间隔 (下限为每分钟通知一次)
localnotifit.repeatInterval = kCFCalendarUnitMinute;
// 提醒内容
localnotifit.alertBody = @"十秒后手机将会爆炸。赶快扔掉";
// 锁屏状态下。“滑动来”(这三个字是系统自己主动出现的)后面紧接着文字就是alertAction
localnotifit.alertAction = @"解锁(进入App)";
// 通知栏里的通知标题
localnotifit.alertTitle = @"提示";
// 默认的通知声音(仅仅有在真机上才会听到)
localnotifit.soundName = UILocalNotificationDefaultSoundName;
// 红色圈圈数字
localnotifit.applicationIconBadgeNumber = 1;
// 通知标识
NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithObject:@"LocalNotificationID" forKey:@"key"];
localnotifit.userInfo = dic;
// 将通知加入到系统中
[[UIApplication sharedApplication] scheduleLocalNotification:localnotifit];
}
// 注冊通知(iOS 8之后的注冊通知方法,iOS 8曾经暂不做介绍)
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
return YES;
}
// 接收到通知后触发的方法,仅仅有在App进入前台的时候才会运行。
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"恭喜你上当了" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"我非常开心", nil];
[UIApplication sharedApplication].applicationIconBadgeNumber = 0;
[alert show];
// 取消通知
// [[UIApplication sharedApplication] cancelAllLocalNotifications];
}