1.什麼是本地推送通知
不需要聯網的情況下,應用程序經由系統發出的通知
2.本地推送的使用場景
定時提醒,如玩游戲、記賬、鬧鐘、備忘錄等
3.實現本地推送通知的步驟
3. 將通知排入到應用程序中
4.點擊通知內容的處理
5.代碼
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { if ([UIDevice currentDevice].systemVersion.doubleValue >= 8.0) {//iOS8以後需要詢問用戶是否允許接收通知 //一下代碼回實現的效果是 //第一次運行程序,系統彈出一個提示框 //詢問用戶是否允許接收通知 UIUserNotificationType noteType = UIUserNotificationTypeAlert | UIUserNotificationTypeSound | UIUserNotificationTypeBadge; UIUserNotificationSettings *setting = [UIUserNotificationSettings settingsForTypes:noteType categories:nil]; [application registerUserNotificationSettings:setting]; } //如果是因為點擊查看了通知而啟動了應用程序 //那麼通知的信息都會存在launchOptions參數中 UILocalNotification *notification = launchOptions[UIApplicationLaunchOptionsLocalNotificationKey]; if (notification != nil) {//點通知進來的 UILabel *label = [[UILabel alloc]init]; label.frame = CGRectMake(0, 40, 300, 200); label.backgroundColor = [UIColor blueColor]; label.numberOfLines = 0; label.font =[UIFont systemFontOfSize:30]; label.textColor = [UIColor whiteColor]; label.text = [NSString stringWithFormat:@"3333333%@",notification.userInfo]; [self.window.rootViewController.view addSubview:label]; [application setApplicationIconBadgeNumber:0]; } return YES; } /* 1.App在前台,通知到了,直接自動執行該方法 2.App在後台,通知到了,點擊查看通知,該方法才執行 3.App已經退出,通知到了,點擊查看通知,此方法不執行,但是didFinishLaunchingWithOptions方法一定會被執行,通知傳入的參數也可以在launching方法中獲取到 */ - (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification { UILabel *label = [[UILabel alloc]init]; label.frame = CGRectMake(0, 250, 300, 200); label.backgroundColor = [UIColor grayColor]; label.numberOfLines = 0; label.font =[UIFont systemFontOfSize:30]; label.textColor = [UIColor whiteColor]; //alertBody用於存儲顯示的通知的文字內容 //uesrInfo用於存儲額外要傳遞的通知內容 label.text = [NSString stringWithFormat:@"%@",notification.userInfo]; [self.window.rootViewController.view addSubview:label]; //去掉應用程序圖標中出現的紅色數字提醒 [application setApplicationIconBadgeNumber:0]; }
//1.創建本地通知對象 UILocalNotification *notification = [[UILocalNotification alloc] init]; //2.設置通知的一些屬性 notification.fireDate = [NSDate dateWithTimeIntervalSinceNow:10];//10秒後發通知 notification.alertBody = @"這是一條新的通知"; notification.userInfo = @{@"name":@"張三", @"age":@20 }; notification.applicationIconBadgeNumber = 2; //3.將通知添加到應用程序的日程清單中 UIApplication *application = [UIApplication sharedApplication]; [application scheduleLocalNotification:notification];
demo:https://github.com/TigerCui/LocalNotification.git