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

iOS 點擊推送跳轉指定頁面:極光推送實作解析

編輯:iOS 開發綜合

推送通知已經成為 App 常見的運營方式。除了打開 App 首頁之外,很多場景還希望使用者點擊通知後,能直接進入指定頁面。本文以極光推送為例,說明如何處理通知跳轉。

一、兩種跳轉方式

點擊推送後,常見有兩種行為:

  • 打開 App,進入首頁。
  • 打開 App,進入指定頁面。

第一種只需要完成極光推送的基本註冊即可。第二種則需要自行解析通知內容,並觸發頁面跳轉。

二、App 未啟動時接收推送

如果 App 尚未啟動,通知內容會透過 launchOptions 傳入。

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    NSDictionary *remoteNotification = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];

    if (remoteNotification) {
        [UIApplication sharedApplication].applicationIconBadgeNumber = 0;

        [self performSelector:@selector(handleRemoteNotification:)
                   withObject:remoteNotification
                   afterDelay:1.0];
    }

    return YES;
}

這裡延遲執行是為了等待 App 的初始界面與根控制器準備完成,避免頁面尚未建立就嘗試跳轉。

三、App 運行中接收推送

如果 App 正在前台或後台運行,可以透過以下 delegate 接收通知。

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    [APService handleRemoteNotification:userInfo];

    if (userInfo) {
        [UIApplication sharedApplication].applicationIconBadgeNumber = 0;

        [[NSNotificationCenter defaultCenter] postNotificationName:@"kPushNotificationReceived"
                                                            object:userInfo];
    }
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    [APService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);

    if (userInfo) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"kPushNotificationReceived"
                                                            object:userInfo];
    }
}

四、頁面監聽通知並跳轉

在需要跳轉的頁面中註冊通知,收到後執行跳轉邏輯。

- (void)viewDidLoad {
    [super viewDidLoad];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(jumpToPushDetail:)
                                                 name:@"kPushNotificationReceived"
                                               object:nil];
}

- (void)jumpToPushDetail:(NSNotification *)notification {
    NSDictionary *userInfo = notification.object;

    // 根據通知內容決定跳轉到哪個頁面
    [self showDetailPageWithUserInfo:userInfo];
}

五、跳轉到指定 Tab

如果希望打開 App 後先切換到第三個 Tab,再進入詳情頁,可以設定 selectedIndex。

_tabBarViewController.selectedIndex = 2;

實際專案中,建議將通知內容設計成結構化資料,例如:

{
    "type": "order",
    "id": "10086"
}

這樣 App 收到通知後,就能根據 type 決定要進入訂單詳情、活動頁或個人中心,讓推送跳轉更穩定、更易維護。

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