ios消息推送機制實現

實現推送功能的前提條件:

1.必須有真機,模擬器是獲取不到deviceToken的。

2.必須有開發者賬號,並且交了99美元。

可能碰到的問題:

1.如果你在設備調試時碰到"未找到應用程序的“aps-environment”的權利字符串"的問題,可能是由於你是先申請的描述文件Provisioning Profiles進行開發的,後來才加入push功能的,這樣的描述文件是不具有push功能的,所以會出現這樣的問題,只要重新生成一個描述文件,替換原來的即可。

Push的原理:

Push 的工作機制可以簡單的概括爲下圖

圖中,Provider是指某個iPhone軟件的Push服務器,這篇文章我將使用.net作爲Provider。
APNS 是Apple Push Notification Service(Apple Push服務器)的縮寫,是蘋果的服務器。

上圖可以分爲三個階段。

第一階段:.net應用程序把要發送的消息、目的iPhone的標識打包,發給APNS。
第二階段:APNS在自身的已註冊Push服務的iPhone列表中,查找有相應標識的iPhone,並把消息發到iPhone。
第三階段:iPhone把發來的消息傳遞給相應的應用程序, 並且按照設定彈出Push通知。

    從上圖我們可以看到。

   1、首先是應用程序註冊消息推送。

   2、 IOS跟APNS Server要deviceToken。應用程序接受deviceToken。

   3、應用程序將deviceToken發送給PUSH服務端程序。

   4、 服務端程序向APNS服務發送消息。

   5、APNS服務將消息發送給iPhone應用程序。

    無論是iPhone客戶端跟APNS,還是Provider和APNS都需要通過證書進行連接的。下面我介紹一下幾種用到的證書。

幾種證書:

一、*.certSigningRequest文件

   1、生成Certificate Signing Request (CSR):

2、填寫你的郵箱和Common Name,這裏填寫爲PushChat。選擇保存到硬盤。

這樣就在本地生成了一個PushChat.certSigningRequest文件。

二、生成*.p12文件

1、導出密鑰,並輸入你的密碼。

輸入你的密碼:

這樣就生成了一個PushChatKey.p12文件。

三、新建一個App ID 和SSL certificate文件

1、用你的付過費的apple帳號登錄到iOS Provisioning Portal。新建一個App ID。

     Description:中輸入PushChat

     Bundle Seed ID:默認選擇Generate New

     Bundle Identifier:輸入com.mysoft.PushChat

    點擊提交

這樣就會生成下面這條記錄:

點擊配置:

出現下面界面,點擊繼續:

這裏我們選擇前面生成好的PushChat.certSigningRequest文件,點擊生成。

正在生成

生成完畢,我們把它下載下來。命名爲aps_developer_identity.cer。

點擊完成,你會發現狀態變成Enabled。

到現在爲止,我們已經生成了3個文件。

1、PushChat.certSigningRequest

2、PushChatKey.p12

3、aps_developer_identity.cer

現在我們創建一個簡單的iPhone應用程序。

1、打開Xcode,選擇創建一個View-based Application。命名如下圖:

2、在PushChatAppDelegate中的didFinishLaunchingWithOptions方法中加入下面代碼:


-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window.rootViewController =self.viewController;
[self.window makeKeyAndVisible];

//Let the device know we want to receive push notifications
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
(UIRemoteNotificationTypeBadge |UIRemoteNotificationTypeSound |UIRemoteNotificationTypeAlert)];

returnYES;
}

通過registerForRemoteNotificationTypes方法,告訴應用程序,能接受push來的通知。

3、在xcode中運行,會彈出下面的提示框:

選擇OK。表示此應用程序開啓消息通知服務。

在 PushChatAppDelegate.m代碼中添加下面方法獲取deviceToken :


-(void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken

{

    NSLog(@"My token is: %@", deviceToken);

    //deviceToken格式化

    if (deviceToken!=nil

    {

        NSString *deviceTokenString = [NSString stringWithFormat:@"%@",deviceToken];

        deviceTokenString = [deviceTokenString stringByReplacingOccurrencesOfString:@" " withString:@""];

        NSRange range = {1,[deviceTokenString length]-2};

        deviceTokenString = [deviceTokenString substringWithRange:range];

        NSLog(@"My token is %@",deviceTokenString);

        /*----------發給服務器--------*/

    }

    

}


-(void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error

{

    NSLog(@"Failed to get token, error: %@", error);



- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo

{

    //軟件icon氣泡提醒

    [UIApplication sharedApplication].applicationIconBadgeNumber  =  0;

    

    

    NSLog(@"Receive remote notification : %@",userInfo);

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"溫馨提示" message:@"推送成功!" delegate:nil cancelButtonTitle:@"確定" otherButtonTitles:nil];

    [alert show];

    [alert release];

}


獲取到的deviceToken,我們可以通過webservice服務提交給.net應用程序,這裏我簡單處理,直接打印出來,拷貝到.net應用環境中使用。

發送通知的.net應用程序出來需要知道deviceToken之外,還需要一個與APNS連接的證書。

這個證書可以通過我們前面生成的兩個文件中得到。

使用OpenSSL生成.net和APNS通信的證書文件。

1、將aps_developer_identity.cer轉換成 aps_developer_identity.pem格式。

openssl x509 -in aps_developer_identity.cer -inform DER -out aps_developer_identity.pem -outform PEM

2、將p12格式的私鑰轉換成pem,需要設置4次密碼,這裏密碼都設置爲:abc123。

openssl pkcs12 -nocerts -out PushChat_Noenc.pem -in PushChat.p12

3、用certificate和the key 創建PKCS#12格式的文件。

openssl pkcs12 -export -in aps_developer_identity.pem -inkey PushChat_Noenc.pem -certfile PushChat.certSigningRequest -name "aps_developer_identity" -out aps_developer_identity.p12

這樣我們就得到了在.net應用程序中使用的證書文件:aps_developer_identity.p12。

在.net應用程序中發送通知。

有個開源的類庫:apns-sharp。

地址是:http://code.google.com/p/apns-sharp/

我們下載源代碼,對裏面的JdSoft.Apple.Apns.Notifications做相應的調整就能用了。

我們根據DeviceToken和p12File對JdSoft.Apple.Apns.Notifications.Test代碼做相應的調整,如下圖。

這樣就OK了。

效果:

通知的代碼:


for(inti =1; i <=count; i++)
{
//Create a new notification to send
Notification alertNotification =newNotification(testDeviceToken);

alertNotification.Payload.Alert.Body =string.Format("Testing {0}...", i);
alertNotification.Payload.Sound ="default";
alertNotification.Payload.Badge =i;

//Queue the notification to be sent
if(service.QueueNotification(alertNotification))
Console.WriteLine("Notification Queued!");
else
Console.WriteLine("Notification Failed to be Queued!");

//Sleep in between each message
if(i <count)
{
Console.WriteLine("Sleeping "+sleepBetweenNotifications +"milliseconds before next Notification...");
System.Threading.Thread.Sleep(sleepBetweenNotifications);
}
}

用手機拍的ipad上面的顯示:



總結:這篇文章主要是詳細的講述了ios消息推送機制的實現,如何通過.net應用程序發送消息給ios應用程序。

轉自:http://2015.iteye.com/blog/1337599

發佈了7 篇原創文章 · 獲贊 0 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章