本地通知:
kvc(鍵值編碼)優點:可以給類的任意實例變量賦值,即使實例變量是私有的
缺點:必須要知道實例變量名,破壞封裝性
KVO (鍵值觀察) ?是一種能使對象獲取到其他對象屬性變化的通知,極大的簡化了代碼,實現KVO模式,被觀察的對象必須是使用KVC來修改它的實例變量,這樣才能被觀察者觀察到。
本地通知是由本地應用觸發的,它是基于時間行為的一種通知形式,例如鬧鐘定時、待辦事項提醒,又或者一個應用在一段時候后不使用通常會提示用戶使用此應用等都是本地通知
由于在iOS8之后,本地通知的寫法有所改變,所以在此之前需要進行版本判斷,如下:
- (BOOL)application:(UIApplication *)applicationdidFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
//判斷版本是不是8.0以上的
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
//注冊通知
UIUserNotificationSettings *settings= [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge |UIUserNotificationTypeSound | UIUserNotificationTypeAlert categories:nil];
[[UIApplication sharedApplication] register UserNotificationSettings:settings];
}
return YES;
}
1、創建UILocalNotification (創建本地通知,注冊)
2、設置處理通知的時間fireDate(觸發通知的時間)
3、配置通知的內容:通知主體、、通知聲音、圖標、數字等
4、配置通知傳遞的自定義參數useInfo(可選)
5、調用通知,可以使用scheduleLocalNotification:按計劃調度一個通知,也可以用presentLocalNotificationNow立即調用通知;
//創建本地通知對象
UILocalNotification*localNotification= [[UILocalNotificationalloc]init];
//設定調度時間,即通知五秒后執行
NSDate*nowDate = [NSDatedate];
[localNotificationsetFireDate:[nowDatedateByAddingTimeInterval:5.0]];
//循環次數,kCFCalendarUnitWeekday一周一次
localNotification.repeatInterval=0;
//當前日歷,使用前最好設置時區等信息以便能夠自動同步時間
//notification.repeatCalendar=[NSCalendar currentCalendar];
//設定時區
[localNotificationsetTimeZone:[NSTimeZonedefaultTimeZone]];
//設置彈出消息
[localNotificationsetAlertBody:@"搶購時間到了"];
[localNotificationsetAlertAction:@"show now"];
//設置通知聲音
[localNotificationsetSoundName:UILocalNotificationDefaultSoundName];
//設置用戶信息
localNotification .userInfo=@{@"id":@1,@"user":@"KenshinCui"};//綁定到通知上的其他附加信息
//設置IconbadgeNumber圖標數字,設置count為全局變量用count來控制圖標數字的增加
count++;
[localNotificationsetApplicationIconBadgeNumber:count];
//應用程序計劃執行通知
[[UIApplicationsharedApplication]scheduleLocalNotification:localNotification];
[[[UIAlertViewalloc]initWithTitle:@"提示"message:@"設置提醒成功"delegate:nilcancelButtonTitle:@"OK"otherButtonTitles:nil,nil]show]
二、程序運行時接收到本地推送信息
-(void)application:(UIApplication*)applicationdidReceiveLocalNotification:(UILocalNotification*)notification{
//這里,你就可以通過notification的useinfo,干一些你想做的事情了
//這里是創建一個KViewController并在點擊通知時切換到該頁面
UIStoryboard*storyboard = [UIStoryboardstoryboardWithName:@"Main"bundle:nil];
KViewController*kViewController =[storyboardinstantiateViewControllerWithIdentifier:@"KViewController"];
UINavigationController*navigationController= (UINavigationController*)self.window.rootViewController;
[navigationControllerpushViewController:kViewControlleranimated:YES];
//圖標數字在每次點開通知后都會減一,知道圖標為0(即圖標消失)不再減
application.applicationIconBadgeNumber-=1;
}
三、移除本地推送
#pragma mark移除本地通知
-(void)removeNotification{
[[UIApplicationsharedApplication]cancelAllLocalNotifications];
}