iOS訊息機制
一、本地推送
iOS 推播通知分為本地推送和遠程推播通知,遠程推播通知就類似於我們平時使用時,即使鎖屏了,也能收到好友發送給我們的訊息,然後在主畫面顯示一個alertview,遠程推送需要遠程服務端的支援,比較複雜. 本地推送相對比較簡單,不需要服務端的支援。
本地通知是NSLocalNotification 實現的,通過執行個體化一個NSLocalNotification類型的通知,同時設定通知的fireDate 屬性,即通知的觸發時間;設定timeZone屬性,即時區;設定alertBody,顯示的內容;設定alertAction;設定soundName,即推送發生時的聲音;設定applicationIconBadgeNumber,即表徵圖上的數字;設定userInfo屬性,該屬性是一個NSDictionary類型的變數。然後在使用UIApplication 的 執行個體方法scheduleLocalNotification:或 presentLocalNotificationNow: 推播通知。
* 1、建立本地推送 *
// 建立一個本地推送 UILocalNotification *notification = [[[UILocalNotification alloc] init] autorelease]; //設定10秒之後 NSDate *pushDate = [NSDate dateWithTimeIntervalSinceNow:10]; if (notification != nil) { // 設定推送時間 notification.fireDate = pushDate; //推送時區設定:從網上搜到 //timeZone是UILocalNotification激發時間是否根據時區改變而改變,如果設定為nil的話, //那麼UILocalNotification將在一段時候後被激發,而不是某一個確切時間被激發。 notification.timeZone = [NSTimeZone defaultTimeZone]; // 設定重複間隔,若不設定將只會推送1次 notification.repeatInterval = kCFCalendarUnitDay; // 推送聲音,(若不設定的話系統推送時會無聲音) notification.soundName = UILocalNotificationDefaultSoundName; // 推送內容,(若不設定,推送中心中不顯示文字,有聲音提示前提是設定有聲音) notification.alertBody = @推送內容; //推送時小表徵圖的設定,PS:這個東西不知道還有啥用 notification.alertLaunchImage=[[NSBundle mainBundle]pathForResource:@3 ofType:@jpg]; //顯示在icon上的紅色圈中的數子 notification.applicationIconBadgeNumber = 1; //設定userinfo 方便在之後需要撤銷的時候使用 NSDictionary *info = [NSDictionary dictionaryWithObject:@nameforKey:@key]; notification.userInfo = info; //講推送設定以及資訊加入 UIApplication* app=[UIApplication sharedApplication]; BOOL status=YES; for (UILocalNotification* notification in app.scheduledLocalNotifications) { if ([notification.userInfo objectForKey:@key]) { status=NO; } } if (status) { //加入推送(只能加入一次) [app scheduleLocalNotification:notification]; } }
* 2、接收本地推送 *
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification*)notification{ UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@iWeibo message:notification.alertBody delegate:nil cancelButtonTitle:@確定 otherButtonTitles:nil]; [alert show]; // 表徵圖上的數字減1 application.applicationIconBadgeNumber -= 1; }
* 3、解除本地推送 *
// 獲得 UIApplication UIApplication *app = [UIApplication sharedApplication]; //擷取本地推送數組 NSArray *localArray = [app scheduledLocalNotifications]; //聲明本地通知對象 UILocalNotification *localNotification; if (localArray) { for (UILocalNotification *noti in localArray) { NSDictionary *dict = noti.userInfo; if (dict) { NSString *inKey = [dict objectForKey:@key]; if ([inKey isEqualToString:@對應的key值]) { if (localNotification){ [localNotification release]; localNotification = nil; } localNotification = [noti retain]; break; } } } //判斷是否找到已經存在的相同key的推送 if (!localNotification) { //不存在初始化 localNotification = [[UILocalNotification alloc] init]; } if (localNotification) { //不推送 取消推送 [app cancelLocalNotification:localNotification]; [localNotification release]; return; } }