推送通知除了提醒使用者外,還可以作為 App 內頁面導航的入口。本文將從通知路由的角度,說明如何在 iOS 中處理點擊推送後跳轉到指定頁面。
通常推送內容會包含一個 type 或 page 欄位,用於標示要跳轉的頁面。例如:
{
"type": "activity",
"id": "2026"
}App 收到通知後,可以根據 type 決定要開啟活動頁、訂單頁或個人中心。
如果使用者是透過點擊推送開啟 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 已經啟動,可以透過 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];
}
}如果頁面位於 TabBarController 的第三個位置,可以先切換選中索引。
self.tabBarController.selectedIndex = 2;若需要同時跳轉到指定頁面,可以在切換 Tab 後再呼叫對應的跳轉方法。
為了避免通知跳轉失效,建議:
透過這種路由方式,推送通知就能成為穩定且可維護的頁面入口。