標籤:
在多數行動裝置 App中任何時候都只能有一個應用程式處於活躍狀態,如果其他應用此刻發生了一些使用者感興趣的那麼通過通知機制就可以告訴使用者此時發生的事情。 iOS中通知機制又叫訊息機制,其包括兩類:一類是本地通知;另一類是推播通知,也叫遠程通知。兩種通知在iOS中的表現一致,可以通過橫幅或者彈出提醒 兩種形式告訴使用者,並且點擊通知可以會開啟應用程式,但是實現原理卻完全不同。今天就和大家一塊去看一下如何在iOS中實現這兩種機制,並且在文章後面會 補充通知中樞的內容避免初學者對兩種概念的混淆。
簡單些了一個關於本地推播通知的demo,可以根據這個進行參考,這個方法是8.0之後才能使用的,所以需要判斷一下系統的版本。
1.註冊本地通知方法
+ (void)registerLocalNotification:(NSInteger)alertTime { UILocalNotification *notification = [[UILocalNotification alloc] init]; // 設定觸發通知的時間 NSDate *fireDate = [NSDate dateWithTimeIntervalSinceNow:alertTime]; NSLog(@"fireDate=%@",fireDate); notification.fireDate = fireDate; // 時區 激發時間是否根據時區改變而改變 notification.timeZone = [NSTimeZone defaultTimeZone]; // 設定重複的間隔 notification.repeatInterval = kCFCalendarUnitSecond; // 通知內容 後台運行時提示的文字 notification.alertBody = @"該起床了..."; notification.applicationIconBadgeNumber = 1; // 通知被觸發時播放的聲音 notification.soundName = UILocalNotificationDefaultSoundName; // 通知參數 NSDictionary *userDict = [NSDictionary dictionaryWithObject:@"開始學習iOS開發了" forKey:@"key"]; notification.userInfo = userDict; // ios8後,需要添加這個註冊,才能得到授權 if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) { UIUserNotificationType type = UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound; UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:type categories:nil]; [[UIApplication sharedApplication] registerUserNotificationSettings:settings]; // 通知重複提示的單位,可以是天、周、月 notification.repeatInterval = NSCalendarUnitDay; } else { // 通知重複提示的單位,可以是天、周、月 notification.repeatInterval = NSDayCalendarUnit; } // 執行通知註冊 [[UIApplication sharedApplication] scheduleLocalNotification:notification];}
取消本地通知的例子:
// 取消某個本地推播通知+ (void)cancelLocalNotificationWithKey:(NSString *)key { // 擷取所有本地通知數組 NSArray *localNotifications = [UIApplication sharedApplication].scheduledLocalNotifications; for (UILocalNotification *notification in localNotifications) { NSDictionary *userInfo = notification.userInfo; if (userInfo) { // 根據設定通知參數時指定的key來擷取通知參數 NSString *info = userInfo[key]; // 如果找到需要取消的通知,則取消 if (info != nil) { [[UIApplication sharedApplication] cancelLocalNotification:notification]; break; } } }}
通知回調的方法:
// 本地通知回呼函數,當應用程式在前台時調用- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification { NSLog(@"noti:%@",notification); // 這裡真實需要處理互動的地方 // 擷取通知所帶的資料 NSString *notMess = [notification.userInfo objectForKey:@"key"]; UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"本地通知...." message:notMess delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; // 更新顯示的徽章個數 NSInteger badge = [UIApplication sharedApplication].applicationIconBadgeNumber; badge--; badge = badge >= 0 ? badge : 0; [UIApplication sharedApplication].applicationIconBadgeNumber = badge; // 推送過一次,不需要顯示推送時,可以取消推送,將添加的推送清除 [HomeViewController cancelLocalNotificationWithKey:@"key"];}
iOS 本地推送