2026-07-29 05:51:15
在 iOS 中,通过推送通知打开指定页面需要正确配置推送权限、处理通知接收逻辑,并根据应用状态(前台/后台)实现页面跳转。以下是具体实现步骤:
1. 配置推送权限在 AppDelegate 中遵循 MPushRegisterDelegate 协议,并设置推送类型(角标、声音、弹窗):
@interface AppDelegate () <MPushRegisterDelegate>@end- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { MPushNotificationConfiguration *configuration = [[MPushNotificationConfiguration alloc] init]; configuration.types = MPushAuthorizationOptionsBadge | MPushAuthorizationOptionsSound | MPushAuthorizationOptionsAlert; [MobPush setupNotification:configuration delegate:self]; return YES;}2. 处理推送消息并跳转页面根据 iOS 版本和通知接收场景(前台/后台),分两种情况处理:
iOS 8-9 兼容处理在 didReceiveRemoteNotification 中区分应用状态:
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler { if (application.applicationState == UIApplicationStateActive) { // 前台收到通知:可弹 Alert 提示用户 } else { // 后台点击通知:解析 URL 并跳转 NSString *url = userInfo[@"url"]; if (url) { UINavigationController *nav = (UINavigationController *)self.window.rootViewController; WebViewController *webVC = [[WebViewController alloc] init]; webVC.url = url; [nav pushViewController:webVC animated:YES]; } } completionHandler(UIBackgroundFetchResultNewData);}iOS 10+ 处理(使用 UNUserNotificationCenter)通过 MPushRegisterDelegate 协议方法处理:
// 后台点击通知- (void)mpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)(void))completionHandler { NSDictionary *userInfo = response.notification.request.content.userInfo; NSString *url = userInfo[@"url"]; if (url) { UINavigationController *nav = (UINavigationController *)self.window.rootViewController; WebViewController *webVC = [[WebViewController alloc] init]; webVC.url = url; [nav pushViewController:webVC animated:YES]; } completionHandler();}// 前台收到通知(可选:弹窗提示)- (void)mpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSUInteger options))completionHandler { completionHandler(UNNotificationPresentationOptionAlert);}3. 推送消息中携带跳转参数在推送后台配置时,需在 payload 中添加自定义字段(如 url):
{ "aps": { "alert": "点击查看详情", "sound": "default" }, "url": "通过以上步骤,即可实现 iOS 推送通知打开指定页面的功能。核心在于正确处理不同 iOS 版本的通知回调,并确保跳转逻辑与视图层级匹配。