通过推送通知打开spicific ViewController
问题描述:
我遇到了一些触发推送通知的麻烦。我需要打开特定的VC,当用户点击具有一些有效载荷的通知时。考虑到情况的应用程序是背景我用这个代码通过推送通知打开spicific ViewController
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
if ((application.applicationState == .inactive || application.applicationState == .background)) {
//open specific VC depends on notification payload
}
}
这里的问题开始:1)我不能从AppDelegate中推VC,只能通过设置新rootController 2)我必须从AppDelegate中的didReceiveRemoteNotification方法使用此代码
答
请参考这个答案:如果应用程序从通知打开How to make your push notification Open a certain view controller?
使用此代码在AppDelegate的检测。在应用程序激活之前,应用程序状态为UIApplicationStateInactive时,请设置初始VC。编写代码来设置您的VC以及VC中的内容。
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{
if(application.applicationState == UIApplicationStateActive) {
//app is currently active, can update badges count here
} else if(application.applicationState == UIApplicationStateBackground){
//app is in background, if content-available key of your notification is set to 1, poll to your backend to retrieve data and update your interface here
} else if(application.applicationState == UIApplicationStateInactive){
//app is transitioning from background to foreground (user taps notification), do what you need when user taps here
self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
UIViewController *viewController = // determine the initial view controller here and instantiate it with [storyboard instantiateViewControllerWithIdentifier:<storyboard id>];
self.window.rootViewController = viewController;
[self.window makeKeyAndVisible];
}
}
@sedq如果是帮助,您可以接受答案。它会帮助别人。 –