2017-07-15 205 views
0

我遇到了一些觸發推送通知的麻煩。我需要打開特定的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方法使用此代碼

回答

3

請參考這個答案:如果應用程序從通知打開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]; 

    } 

} 
+0

@sedq如果是幫助,您可以接受答案。它會幫助別人。 –