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

iOS 推送通知跳轉指定頁面:通知路由與頁面處理

編輯:iOS 開發綜合

推送通知除了提醒使用者外,還可以作為 App 內頁面導航的入口。本文將從通知路由的角度,說明如何在 iOS 中處理點擊推送後跳轉到指定頁面。

一、通知內容決定跳轉目標

通常推送內容會包含一個 type 或 page 欄位,用於標示要跳轉的頁面。例如:

{
    "type": "activity",
    "id": "2026"
}

App 收到通知後,可以根據 type 決定要開啟活動頁、訂單頁或個人中心。

二、App 啟動時取得通知

如果使用者是透過點擊推送開啟 App,通知內容會出現在 launchOptions 中。

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

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

        [self performSelector:@selector(handlePushRoute:)
                   withObject:remoteNotification
                   afterDelay:0.5];
    }

    return YES;
}

三、App 運行中接收通知

如果 App 已經啟動,可以透過 didReceiveRemoteNotification: 接收。

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

    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;

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

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

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

四、在頁面中註冊通知

頁面可以監聽通知,收到後再決定是否跳轉。

- (void)viewDidLoad {
    [super viewDidLoad];

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

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

    NSString *type = userInfo[@"type"];

    if ([type isEqualToString:@"activity"]) {
        [self showActivityPage:userInfo];
    } else if ([type isEqualToString:@"order"]) {
        [self showOrderPage:userInfo];
    }
}

五、跳轉到指定 Tab

如果頁面位於 TabBarController 的第三個位置,可以先切換選中索引。

self.tabBarController.selectedIndex = 2;

若需要同時跳轉到指定頁面,可以在切換 Tab 後再呼叫對應的跳轉方法。

六、實務建議

為了避免通知跳轉失效,建議:

  • 延遲執行跳轉,等待根控制器準備完成。
  • 通知內容結構化,避免依賴不可控的欄位。
  • 對未知 type 提供預設處理,避免無回應。
  • 在離開頁面時移除通知監聽,避免重複接收。

透過這種路由方式,推送通知就能成為穩定且可維護的頁面入口。

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