您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 開發中的兩種消息通知機制詳解

編輯:iOS 開發綜合

iOS 中的通知機制又叫消息機制,主要包括兩類:一類是本地通知,另一類是推送通知(也叫遠程通知)。兩種通知在 iOS 中的表現一致,都可以通過橫幅或彈出提醒的形式告知用戶,點擊通知還能進入應用程序,但它們的實現原理卻完全不同。

本地通知

本地通知的基本流程如下:

1. 創建 UILocalNotification。
2. 設置處理通知的時間 fireDate。
3. 配置通知的內容:通知主體、通知聲音、圖標數字等。
4. 配置通知傳遞的自定義數據參數 userInfo(這一步可選)。
5. 調用通知,可以用 scheduleLocalNotification: 按計劃調度一個通知,也可以用 presentLocalNotificationNow: 立即調用通知。

下面以「程序更新後、用戶長期未使用」的提醒為例,對本地通知做一個簡單的認識。這個過程幾乎不涉及界面操作,所有邏輯都放在 AppDelegate 中:進入應用後如果尚未註冊通知,需要先註冊通知、請求用戶允許;一旦調用完註冊方法,無論用戶是否允許,此刻都會觸發應用程序的 - (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings 代理方法,在這個方法中根據用戶的選擇判斷:如果允許通知,則按照前面的步驟創建通知並在一段時間後執行。

 #import "AppDelegate.h" #import "KCMainViewController.h" @interface AppDelegate () @end @implementation AppDelegate #pragma mark - 應用代理方法 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { _window=[[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds]; _window.backgroundColor =[UIColor colorWithRed:249/255.0 green:249/255.0 blue:249/255.0 alpha:1]; //設置全局導航條風格和顏色 [[UINavigationBar appearance] setBarTintColor:[UIColor colorWithRed:23/255.0 green:180/255.0 blue:237/255.0 alpha:1]]; [[UINavigationBar appearance] setBarStyle:UIBarStyleBlack]; KCMainViewController *mainController=[[KCMainViewController alloc]init]; _window.rootViewController=mainController; [_window makeKeyAndVisible]; //如果已經獲得發送通知的授權則創建本地通知,否則請求授權(注意:如果不請求授權在設置中是沒有對應的通知設置項的,也就是說如果從來沒有發送過請求,即使通過設置也打不開消息允許設置) if ([[UIApplication sharedApplication]currentUserNotificationSettings].types!=UIUserNotificationTypeNone) { [self addLocalNotification]; }else{ [[UIApplication sharedApplication]registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]]; } return YES; } #pragma mark 調用過用戶注冊通知方法之後執行(也就是調用完registerUserNotificationSettings:方法之後執行) -(void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings{ if (notificationSettings.types!=UIUserNotificationTypeNone) { [self addLocalNotification]; } } #pragma mark 進入前台後設置消息信息 -(void)applicationWillEnterForeground:(UIApplication *)application{ [[UIApplication sharedApplication]setApplicationIconBadgeNumber:0];//進入前台取消應用消息圖標 } #pragma mark - 私有方法 #pragma mark 添加本地通知 -(void)addLocalNotification{ //定義本地通知對象 UILocalNotification *notification=[[UILocalNotification alloc]init]; //設置調用時間 notification.fireDate=[NSDate dateWithTimeIntervalSinceNow:10.0];//通知觸發的時間,10s以後 notification.repeatInterval=2;//通知重復次數 //notification.repeatCalendar=[NSCalendar currentCalendar];//當前日歷,使用前最好設置時區等信息以便能夠自動同步時間 //設置通知屬性 notification.alertBody=@"最近添加了諸多有趣的特性,是否立即體驗?"; //通知主體 notification.applicationIconBadgeNumber=1;//應用程序圖標右上角顯示的消息數 notification.alertAction=@"打開應用"; //待機界面的滑動動作提示 notification.alertLaunchImage=@"Default";//通過點擊通知打開應用時的啟動圖片,這裡使用程序啟動圖片 //notification.soundName=UILocalNotificationDefaultSoundName;//收到通知時播放的聲音,默認消息聲音 notification.soundName=@"msg.caf";//通知聲音(需要真機才能聽到聲音) //設置用戶信息 notification.userInfo=@{@"id":@1,@"user":@"Kenshin Cui"};//綁定到通知上的其他附加信息 //調用通知 [[UIApplication sharedApplication] scheduleLocalNotification:notification]; } #pragma mark 移除本地通知,在不需要此通知時記得移除 -(void)removeNotification{ [[UIApplication sharedApplication] cancelAllLocalNotifications]; } @end

依次可以看到:1. 請求獲得用戶允許通知的效果;2. 應用退出後彈出通知的效果;3. 鎖屏狀態下的通知效果(從這個界面可以看到 alertAction 被配置為「打開應用」)。

要驗證 userInfo 的傳遞,可以通過下面這段代碼,在應用啟動或接收通知時把 userInfo 寫入本地文件系統:

 #import "AppDelegate.h" #import "KCMainViewController.h" @interface AppDelegate () @end @implementation AppDelegate #pragma mark - 應用代理方法 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { _window=[[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds]; _window.backgroundColor =[UIColor colorWithRed:249/255.0 green:249/255.0 blue:249/255.0 alpha:1]; //設置全局導航條風格和顏色 [[UINavigationBar appearance] setBarTintColor:[UIColor colorWithRed:23/255.0 green:180/255.0 blue:237/255.0 alpha:1]]; [[UINavigationBar appearance] setBarStyle:UIBarStyleBlack]; KCMainViewController *mainController=[[KCMainViewController alloc]init]; _window.rootViewController=mainController; [_window makeKeyAndVisible]; //添加通知 [self addLocalNotification]; //接收通知參數 UILocalNotification *notification=[launchOptions valueForKey:UIApplicationLaunchOptionsLocalNotificationKey]; NSDictionary *userInfo= notification.userInfo; [userInfo writeToFile:@"/Users/kenshincui/Desktop/didFinishLaunchingWithOptions.txt" atomically:YES]; NSLog(@"didFinishLaunchingWithOptions:The userInfo is %@.",userInfo); return YES; } #pragma mark 接收本地通知時觸發 -(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{ NSDictionary *userInfo=notification.userInfo; [userInfo writeToFile:@"/Users/kenshincui/Desktop/didReceiveLocalNotification.txt" atomically:YES]; NSLog(@"didReceiveLocalNotification:The userInfo is %@",userInfo); } #pragma mark 調用過用戶注冊通知方法之後執行(也就是調用完registerUserNotificationSettings:方法之後執行) -(void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings{ if (notificationSettings.types!=UIUserNotificationTypeNone) { [self addLocalNotification]; } } #pragma mark 進入前台後設置消息信息 -(void)applicationWillEnterForeground:(UIApplication *)application{ [[UIApplication sharedApplication]setApplicationIconBadgeNumber:0];//進入前台取消應用消息圖標 } #pragma mark - 私有方法 #pragma mark 添加本地通知 -(void)addLocalNotification{ //定義本地通知對象 UILocalNotification *notification=[[UILocalNotification alloc]init]; //設置調用時間 notification.fireDate=[NSDate dateWithTimeIntervalSinceNow:10.0];//通知觸發的時間,10s以後 notification.repeatInterval=2;//通知重復次數 //notification.repeatCalendar=[NSCalendar currentCalendar];//當前日歷,使用前最好設置時區等信息以便能夠自動同步時間 //設置通知屬性 notification.alertBody=@"最近添加了諸多有趣的特性,是否立即體驗?"; //通知主體 notification.applicationIconBadgeNumber=1;//應用程序圖標右上角顯示的消息數 notification.alertAction=@"打開應用"; //待機界面的滑動動作提示 notification.alertLaunchImage=@"Default";//通過點擊通知打開應用時的啟動圖片 //notification.soundName=UILocalNotificationDefaultSoundName;//收到通知時播放的聲音,默認消息聲音 notification.soundName=@"msg.caf";//通知聲音(需要真機) //設置用戶信息 notification.userInfo=@{@"id":@1,@"user":@"Kenshin Cui"};//綁定到通知上的其他額外信息 //調用通知 [[UIApplication sharedApplication] scheduleLocalNotification:notification]; } @end

上面的程序可以分兩種情況運行:一種是啟動程序後關閉它,等接收到通知後點擊通知重新進入程序;另一種是啟動程序後進入後台(其實在前台也可以,但為了明顯體驗這個過程建議進入後台),接收到通知後點擊通知進入應用。這兩種情況會分別調用前面提到的不同方法來接收 userInfo 並寫入本地文件系統。有了 userInfo,一般就可以根據這個信息做一些處理,例如根據不同的參數導航到不同界面——假設是更新通知,就導航到更新內容界面等等。

推送通知

與本地通知不同,推送通知是由應用服務提供商發起的,通過蘋果的 APNs(Apple Push Notification Server)發送到應用客戶端。下面是蘋果官方關於推送通知過程的示意圖:

推送通知的過程可以分為以下幾步:

1. 應用服務提供商從服務器端把要發送的消息和設備令牌(device token)發送給蘋果的消息推送服務器 APNs。
2. APNs 根據設備令牌,在已註冊的設備(iPhone、iPad、iTouch、Mac 等)中查找對應設備,把消息發送給相應的設備。
3. 客戶端設備把接收到的消息傳遞給相應的應用程序,應用程序根據用戶設置彈出通知消息。

當然,這只是一個簡單的流程,有了它我們仍舊無從下手編寫程序。把上面的流程細化,可以得到如下流程圖(圖片來自互聯網),這個過程也會說明如何在程序中完成這些步驟:

1. 應用程序註冊 APNs 推送消息

說明:

a. 只有註冊過的應用才有可能接收到消息,程序中通常通過 UIApplication 的 registerUserNotificationSettings: 方法註冊。iOS 8 中通知註冊的方法發生了改變,如果是 iOS 7 及之前版本,請參考其他代碼。

b. 註冊之前有兩個前提條件必須準備好:開發配置文件(provisioning profile,即 .mobileprovision 後綴的文件)的 App ID 不能使用通配 ID,必須使用指定 App ID,並且生成配置文件時要選擇 Push Notifications 服務,一般的開發配置文件無法完成註冊;應用的 Bundle Identifier 必須與生成配置文件使用的 App ID 完全一致。

2. iOS 從 APNs 接收 device token,並在應用程序中獲取 device token

說明:

a. 在 UIApplication 的 -(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken 代理方法中獲取令牌,此方法發生在註冊之後。

b. 如果無法正確獲得 device token,可以在 UIApplication 的 -(void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error 代理方法中查看詳細錯誤信息,此方法發生在獲取 device token 失敗之後。

c. 必須真機調試,模擬器無法獲取 device token。

3. iOS 應用把 device token 發送給應用程序提供商,告訴服務器端當前設備允許接收消息

說明:

a. device token 的生成算法只有 Apple 掌握,為了確保算法發生變化後仍能正常接收服務器端發送的通知,每次應用啟動都應重新獲取 device token(注意:獲取 device token 不會造成性能問題,蘋果官方已做過優化)。

b. 通常可以建立一個網絡連接,把 device token 發送給應用程序提供商的服務器端。這個過程中最好把上一次獲得的 device token 存儲起來,避免重複發送;一旦發現 device token 發生變化,最好把原有的 device token 一併發送給服務器端,服務器端刪除舊令牌、存儲新令牌,避免發送無效消息。

4. 應用程序提供商在服務器端根據前面發送過來的 device token 組織信息,發送給 APNs

說明:

a. 發送時要指定 device token 和消息內容,並完全按照蘋果官方的消息格式組織內容,通常可以借助第三方消息推送框架來完成。

5. APNs 根據消息中的 device token 查找已註冊的設備,推送消息

說明:

a. 正常情況下可以根據 device token 把消息成功推送到客戶端設備,但也不能排除用戶卸載程序的情況。此時推送消息失敗,APNs 會把這個錯誤通知服務器端以避免資源浪費(服務器端此時可以根據錯誤刪除已存儲的 device token,下次不再發送)。

下面簡單演示一下推送通知的流程。

首先看 iOS 客戶端代碼:

 #import "AppDelegate.h" #import "KCMainViewController.h" @interface AppDelegate () @end @implementation AppDelegate #pragma mark - 應用程序代理方法 #pragma mark 應用程序啟動之後 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { _window=[[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds]; _window.backgroundColor =[UIColor colorWithRed:249/255.0 green:249/255.0 blue:249/255.0 alpha:1]; //設置全局導航條風格和顏色 [[UINavigationBar appearance] setBarTintColor:[UIColor colorWithRed:23/255.0 green:180/255.0 blue:237/255.0 alpha:1]]; [[UINavigationBar appearance] setBarStyle:UIBarStyleBlack]; KCMainViewController *mainController=[[KCMainViewController alloc]init]; _window.rootViewController=mainController; [_window makeKeyAndVisible]; //注冊推送通知(注意iOS8注冊方法發生了變化) [application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]]; [application registerForRemoteNotifications]; return YES; } #pragma mark 注冊推送通知之後 //在此接收設備令牌 -(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{ [self addDeviceToken:deviceToken]; NSLog(@"device token:%@",deviceToken); } #pragma mark 獲取device token失敗後 -(void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{ NSLog(@"didFailToRegisterForRemoteNotificationsWithError:%@",error.localizedDescription); [self addDeviceToken:nil]; } #pragma mark 接收到推送通知之後 -(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{ NSLog(@"receiveRemoteNotification,userInfo is %@",userInfo); } #pragma mark - 私有方法 /** * 添加設備令牌到服務器端 * * @param deviceToken 設備令牌 */ -(void)addDeviceToken:(NSData *)deviceToken{ NSString *key=@"DeviceToken"; NSData *oldToken= [[NSUserDefaults standardUserDefaults]objectForKey:key]; //如果偏好設置中的已存儲設備令牌和新獲取的令牌不同則存儲新令牌並且發送給服務器端 if (![oldToken isEqualToData:deviceToken]) { [[NSUserDefaults standardUserDefaults] setObject:deviceToken forKey:key]; [self sendDeviceTokenWidthOldDeviceToken:oldToken newDeviceToken:deviceToken]; } } -(void)sendDeviceTokenWidthOldDeviceToken:(NSData *)oldToken newDeviceToken:(NSData *)newToken{ //注意一定確保真機可以正常訪問下面的地址 NSString *urlStr=@"https://192.168.1.101/RegisterDeviceToken.aspx"; urlStr=[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSURL *url=[NSURL URLWithString:urlStr]; NSMutableURLRequest *requestM=[NSMutableURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:10.0]; [requestM setHTTPMethod:@"POST"]; NSString *bodyStr=[NSString stringWithFormat:@"oldToken=%@&newToken=%@",oldToken,newToken]; NSData *body=[bodyStr dataUsingEncoding:NSUTF8StringEncoding]; [requestM setHTTPBody:body]; NSURLSession *session=[NSURLSession sharedSession]; NSURLSessionDataTask *dataTask= [session dataTaskWithRequest:requestM completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { if (error) { NSLog(@"Send failure,error is :%@",error.localizedDescription); }else{ NSLog(@"Send Success!"); } }]; [dataTask resume]; } @end

iOS 客戶端代碼比較簡單:註冊推送通知,獲取 device token 並存儲到偏好設置中,如果新獲取的 device token 與偏好設置中存儲的不同,就發送給服務器端,更新服務器端的 device token 列表。

其次,由於 device token 需要發送給服務器端,這裡用一個 Web 應用作為服務器端來接收 device token。此處使用 ASP.NET 程序處理令牌接收註冊工作,當然你用其他技術同樣沒問題。下面是對應的後台代碼:

 using System; using System.Collections.Generic; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using CMJ.Framework.Data; namespace WebServer { public partial class RegisterDeviceToken : System.Web.UI.Page { private string _appID = @"com.cmjstudio.pushnotification"; private SqlHelper _helper = new SqlHelper(); protected void Page_Load(object sender, EventArgs e) { try { string oldToken = Request["oldToken"] + ""; string newToken = Request["newToken"] + ""; string sql = ""; //如果傳遞舊的設備令牌則刪除舊令牌添加新令牌 if (oldToken != "") { sql = string.Format("DELETE FROM dbo.Device WHERE AppID='{0}' AND DeviceToken='{1}';", _appID, oldToken); } sql += string.Format(@"IF NOT EXISTS (SELECT ID FROM dbo.Device WHERE AppID='{0}' AND DeviceToken='{1}') INSERT INTO dbo.Device ( AppID, DeviceToken ) VALUES ( N'{0}', N'{1}');", _appID, newToken); _helper.ExecuteNonQuery(sql); Response.Write("注冊成功!"); } catch(Exception ex) { Response.Write("注冊失敗,錯誤詳情:"+ex.ToString()); } } } }

這個過程主要是把 device token 保存到數據庫中,當然如果同時傳遞了舊的設備令牌,還需要先刪除舊的設備令牌。這裡簡單地在數據庫中創建了一張 Device 表來保存設備令牌,其中記錄了應用程序 Id 和設備令牌。

第三步是服務器端發送消息。如果要給 APNs 發送消息,就必須按照 Apple 的標準消息格式組織內容。好在目前已經有很多開源的第三方類庫可供使用,消息具體如何包裝完全不用自己操心。這裡使用一個開源類庫 Push Sharp 給 APNs 發送消息,除了 Apple 設備,Push Sharp 還支持 Android、Windows Phone 等多種設備,更多內容可參照官方說明。前面說過,要開發消息推送應用不能使用一般的開發配置文件;這裡還要注意:如果服務器端要給 APNs 發送消息,其密鑰必須是通過「APNs Development iOS」類型的證書導出的,一般的「iOS Development」類型證書導出的密鑰無法用作服務器端發送密鑰。下面通過一個簡單的 WinForm 程序調用 Push Sharp 給 APNs 發送消息,這裡讀取之前 Device 表中的所有設備令牌,循環發送消息:

 using System; using System.IO; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using PushSharp; using PushSharp.Apple; using CMJ.Framework.Data; using CMJ.Framework.Logging; using CMJ.Framework.Windows.Forms; namespace PushNotificationServer { public partial class frmMain : PersonalizeForm { private string _appID = @"com.cmjstudio.pushnotification"; private SqlHelper _helper = new SqlHelper(); public frmMain() { InitializeComponent(); } private void btnClose_Click(object sender, EventArgs e) { this.Close(); } private void btnSend_Click(object sender, EventArgs e) { List deviceTokens = GetDeviceToken(); SendMessage(deviceTokens, tbMessage.Text); } #region 發送消息 ///  /// 取得所有設備令牌 ///  /// 設備令牌 private List GetDeviceToken() { List deviceTokens = new List(); string sql = string.Format("SELECT DeviceToken FROM dbo.Device WHERE AppID='{0}'",_appID); DataTable dt = _helper.GetDataTable(sql); if(dt.Rows.Count>0) { foreach(DataRow dr in dt.Rows) { deviceTokens.Add((dr["DeviceToken"]+"").TrimStart('<').TrimEnd('>').Replace(" ","")); } } return deviceTokens; } ///  /// 發送消息 ///  ///設備令牌 ///消息內容 private void SendMessage(List deviceToken, string message) { //創建推送對象 var pusher = new PushBroker(); pusher.OnNotificationSent += pusher_OnNotificationSent;//發送成功事件 pusher.OnNotificationFailed += pusher_OnNotificationFailed;//發送失敗事件 pusher.OnChannelCreated += pusher_OnChannelCreated; pusher.OnChannelDestroyed += pusher_OnChannelDestroyed; pusher.OnChannelException += pusher_OnChannelException; pusher.OnDeviceSubscriptionChanged += pusher_OnDeviceSubscriptionChanged; pusher.OnDeviceSubscriptionExpired += pusher_OnDeviceSubscriptionExpired; pusher.OnNotificationRequeue += pusher_OnNotificationRequeue; pusher.OnServiceException += pusher_OnServiceException; //注冊推送服務 byte[] certificateData = File.ReadAllBytes(@"E:\KenshinCui_Push.p12"); pusher.RegisterAppleService(new ApplePushChannelSettings(certificateData, "123")); foreach (string token in deviceToken) { //給指定設備發送消息 pusher.QueueNotification(new AppleNotification() .ForDeviceToken(token) .WithAlert(message) .WithBadge(1) .WithSound("default")); } } void pusher_OnServiceException(object sender, Exception error) { Console.WriteLine("消息發送失敗,錯誤詳情:" + error.ToString()); PersonalizeMessageBox.Show(this, "消息發送失敗,錯誤詳情:" + error.ToString(), "系統提示"); } void pusher_OnNotificationRequeue(object sender, PushSharp.Core.NotificationRequeueEventArgs e) { Console.WriteLine("pusher_OnNotificationRequeue"); } void pusher_OnDeviceSubscriptionExpired(object sender, string expiredSubscriptionId, DateTime expirationDateUtc, PushSharp.Core.INotification notification) { Console.WriteLine("pusher_OnDeviceSubscriptionChanged"); } void pusher_OnDeviceSubscriptionChanged(object sender, string oldSubscriptionId, string newSubscriptionId, PushSharp.Core.INotification notification) { Console.WriteLine("pusher_OnDeviceSubscriptionChanged"); } void pusher_OnChannelException(object sender, PushSharp.Core.IPushChannel pushChannel, Exception error) { Console.WriteLine("消息發送失敗,錯誤詳情:" + error.ToString()); PersonalizeMessageBox.Show(this, "消息發送失敗,錯誤詳情:" + error.ToString(), "系統提示"); } void pusher_OnChannelDestroyed(object sender) { Console.WriteLine("pusher_OnChannelDestroyed"); } void pusher_OnChannelCreated(object sender, PushSharp.Core.IPushChannel pushChannel) { Console.WriteLine("pusher_OnChannelCreated"); } void pusher_OnNotificationFailed(object sender, PushSharp.Core.INotification notification, Exception error) { Console.WriteLine("消息發送失敗,錯誤詳情:" + error.ToString()); PersonalizeMessageBox.Show(this, "消息發送失敗,錯誤詳情:"+error.ToString(), "系統提示"); } void pusher_OnNotificationSent(object sender, PushSharp.Core.INotification notification) { Console.WriteLine("消息發送成功!"); PersonalizeMessageBox.Show(this, "消息發送成功!", "系統提示"); } #endregion } } 

服務器端消息發送應用的運行效果:

iOS 客戶端接收到的消息效果:

至此,通過服務器端應用可以順利把消息發送給 APNs,iOS 應用也已成功接收到推送消息。

補充——iOS 開發證書、秘鑰

iOS 開發過程中,如果需要真機調試或發布,就要註冊申請很多證書,對於初學者往往容易迷惑,再加上本文牽扯到一些特殊配置,這裡就簡單說明一下 iOS 開發常用的證書和秘鑰等。

證書

iOS 常用的證書包括開發證書和發布證書。無論是真機調試還是最終發布應用到 App Store,這兩個證書都是必須的,是 iOS 開發的基本證書。

a. 開發證書:又分為普通開發證書和推送證書。如果只是普通應用,前者即可滿足;但如果開發推送應用,則必須使用推送證書。

b. 發布證書:又分為普通發布證書、推送證書、Pass Type ID 證書、站點發布證書、VoIP 服務證書、蘋果支付證書。同樣地,對於需要使用特殊服務的應用,則必須選擇對應的證書。

應用標識

App ID,應用程序的唯一標識,對應 iOS 應用的 Bundle Identifier。App ID 在蘋果開發者中心分為通配應用 ID 和明確的應用 ID:前者一般用於普通應用開發,一個 ID 可以適用於多個不同標識的應用;而對於使用消息推送、Passbook、站點發布、iCloud 等服務的應用,則必須配置明確的應用 ID。

設備標識

UDID,用於標識每一台硬件設備的標示符。注意它不是 device token——device token 是根據 UDID 使用一個只有 Apple 自己才知道的算法生成的一組標示符。

配置簡介

Provisioning Profiles,平時又稱 PP 文件。它是把 UDID、App ID、開發證書打包在一起的配置文件,同樣分為開發和發布兩類。

秘鑰

在申請開發證書時,必須先提交一個秘鑰請求文件。對於生成秘鑰請求文件的那台 Mac,如果要做開發,只需下載證書和配置簡介即可;但如果想在其他機器上開發,就必須把證書中的秘鑰導出(導出後是一個 .p12 文件),然後導入其他機器。同時,對於類似推送服務器端應用如果要給 APNs 發送消息,同樣需要使用 .p12 秘鑰文件,而且這個秘鑰文件必須是推送證書導出的對應秘鑰。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved