注:按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];www.2cto.com
[[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];
}