推送通知已經成為 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 正在前台或後台運行,可以透過以下 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];
}如果希望打開 App 後先切換到第三個 Tab,再進入詳情頁,可以設定 selectedIndex。
_tabBarViewController.selectedIndex = 2;實際專案中,建議將通知內容設計成結構化資料,例如:
{
"type": "order",
"id": "10086"
}這樣 App 收到通知後,就能根據 type 決定要進入訂單詳情、活動頁或個人中心,讓推送跳轉更穩定、更易維護。