Just a Computer Graphics Studio & My Life

前一陣子介紹圖解APP訊息推播流程,是關於iOS和Android兩大平台從發送到接收的整個過程,現在我們想要實作處理推送通知 (Process Push Notification),iOS SDK已經包好方法只要註冊成功後,就能透過某個method來繼續接下來的處理。可以先參考圖解蘋果推播通知服務 (Apple Push Notification Service)

Apple Push Notification Service00002

現在有兩個case要處理:

  1. app在前景與背景運作時(已在記憶體中)
  2. app第一次載入時(沒在記憶體中)

Parse Push Notification

我想要從收到通知的列表中點擊來觸發,第一點沒什麼問題,第二點就無法觸發該method:

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

怎麼辦呢?還沒開啟app,最先會經過這method:

– (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions;

於是乎我們可以在Appdelegate.m中實作:

/**
 Theme: Process Push Notification
 IDE: Xcode 7
 Language: Objective C
 Date: 105/04/19
 Author: HappyMan
 Blog: https://cg2010studio.wordpress.com/
 */
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

        NSDictionary *remoteNotif = [launchOptions objectForKey: UIApplicationLaunchOptionsRemoteNotificationKey];

        // Accept push notification when app is not open
        if (remoteNotif) {
            [self handleRemoteNotification:application userInfo:remoteNotif];
            return YES;
        }

        return YES;
}

// Accept push notification when app is open (foreground and background)
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    [self handleRemoteNotification:application didReceiveRemoteNotification:userInfo];
}

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

// Do whatever you want here
}

我用iPhone 5c iOS 7測試,真的是在載入時馬上進行我想跳轉到特定頁面的動作呢!

參考:Calling didReceiveRemoteNotification when app is launching for the first time

廣告

發表留言

在下方填入你的資料或按右方圖示以社群網站登入:

WordPress.com Logo

您的留言將使用 WordPress.com 帳號。 登出 / 變更 )

Twitter picture

您的留言將使用 Twitter 帳號。 登出 / 變更 )

Facebook照片

您的留言將使用 Facebook 帳號。 登出 / 變更 )

Google+ photo

您的留言將使用 Google+ 帳號。 登出 / 變更 )

連結到 %s

標籤雲

%d 位部落客按了讚: