2011/06/22

Apple Push Notification Service - 推播服務

最近在研究怎麼收送push notification,以及怎麼架設notification server。


推播服務的介紹及運作方式可以參考:
簡單來說就是每個iOS的app第一次開啓時會向apple註冊推播服務,然後得到專屬的device token,可以想像成擁有專屬的tunnel,再來只要向apple的server傳送message(JSON格式),並帶上target device token,server就會自動幫你轉傳給對方。



寫一個小小的測試程式
網站說明非常清楚,大致上的流程如下:
  • 登入 iOS dev center 然後創建一個新的 App ID
  • 開啓 push notification service
  • 下載 "Development Push SSL Certificate" 及 "Provisioning Profile"
Receiver (iOS app):
  • 安裝 provisioning profile
  • 設定 identifier
  • Write the code to register from remote notification server and get "device token"
範例:
要求使用者開啓 Push notification 服務
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [[UIApplication sharedApplication]registerForRemoteNotificationTypes:
  (UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];
}

Implement 3個 delegate
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{ 
    /* Get device token */ 
    NSString *strDevToken = [NSString stringWithFormat:@"%@", deviceToken];

    /* Replace '<', '>' and ' ' */
    NSCharacterSet *charDummy = [NSCharacterSet characterSetWithCharactersInString:@"<> "];
    strDevToken = [[strDevToken componentsSeparatedByCharactersInSet: charDummy] componentsJoinedByString: @""];
    NSLog(@"Device token=[%@]", strDevToken);

    /* 可以把token傳到server,之後server就可以靠它送推播給使用者了 */
}

- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err
{
    NSLog(@"Error=[%@]", err);
    // TODO: when user do not allow push notification service, pop the warning message.
}

// This function called when receive notification and app is in the foreground.
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo 
{
    /* 把收到的推播列舉出來 */
    for (id key in userInfo) {
        NSLog(@"Key=[%@], Value=[%@]", key, [userInfo objectForKey:key]); 
    }

    /* 印出 Badge number */
    NSLog(@"Badge: %@", [[userInfo objectForKey:@"aps"] objectForKey:@"badge"];

}

Sender (MacOS app):
  • Base on sample code "PushMeBaby"
  • Install "Development Push SSL Certificate"
  • Set target device token then send

參考資料


至於要如何架設APNS,可以參考下一篇:架設 Apple Push Notification Provider Server


沒有留言:

張貼留言