2015-06-03 25 views
5

我的目標是編寫一個代碼,當用戶得到推送通知時,我希望該用戶被重定向到另一個視圖。 如果用戶配備了推送通知,如果他已經第一觀察控制器(洗塵屏幕等(但不登錄))在AppDelegate中用推送通知重定向視圖

var rootViewController = self.window!.rootViewController as! ViewController 
rootViewController.performSegueWithIdentifier("hospitalSegue", sender: self) 

這對夫妻卻行代碼工作,如果用戶已經在另一個視圖控制器(登錄/登錄/用戶頁面等)這段代碼無法正常工作和重定向。 我嘗試了一切,但仍然無法提供解決方案。我的最終目標是:

if let rootViewController = self.window!.rootViewController as? ViewController 
{ 
    var rootView: UserViewController = UserViewController() 

    if let window = self.window{ 
     window.rootViewController = rootView 
    } 

    rootViewController.performSegueWithIdentifier("hospitalSegue", sender: self) 
    println(self.window?.rootViewController) 
} 

任何人都可以給我一個想法嗎?

+0

聽起來像一個偉大的想法。你如何收到推送通知?也許你可以在InterfaceBuilder中給我們一個你的視圖的概述,它取決於你的層次結構,如何重定向到一個不同的視圖。 –

+0

你是以模態方式顯示'UIViewController'嗎? – Lefteris

+2

使用NSNotificationCenter。 https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSNotificationCenter_Class/ –

回答

1

答案代碼是Objective-C,我想談談邏輯。爲此,當您創建推送通知時,您必須設置userInfo值以通過推送通知傳遞數據。

使用該委託方法:application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler

您可以決定是否其查看您想處理USERINFO

NSDictionary *segueDictionary = [userInfo valueForKey:@"aps"]; 

NSString *segueName=[[NSString alloc]initWithFormat:@"%@",[segueDictionary valueForKey:@"segueName"]]; 

if([segueName isEqualToString:@"hospitalSegue"]) 
{ 
// implement your code to redirect 
} 
0

答案代碼顯示是Objective-C中,你可以從應用程序委託prentviewcontroller使用下面的方法我解決了這個問題,使用下面的代碼:

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo 
{ 
     [[self topViewController]presentViewController:nav animated:YES completion:nil]; 
} 

- (UIViewController*)topViewController { 
    return [self topViewControllerWithRootViewController:[UIApplication sharedApplication].keyWindow.rootViewController]; 
} 

- (UIViewController*)topViewControllerWithRootViewController:(UIViewController*)rootViewController { 
    if ([rootViewController isKindOfClass:[UITabBarController class]]) { 
     UITabBarController* tabBarController = (UITabBarController*)rootViewController; 
     return [self topViewControllerWithRootViewController:tabBarController.selectedViewController]; 
    } else if ([rootViewController isKindOfClass:[UINavigationController class]]) { 
     UINavigationController* navigationController = (UINavigationController*)rootViewController; 
     return [self topViewControllerWithRootViewController:navigationController.visibleViewController]; 
    } else if (rootViewController.presentedViewController) { 
     UIViewController* presentedViewController = rootViewController.presentedViewController; 
     return [self topViewControllerWithRootViewController:presentedViewController]; 
    } else { 
     return rootViewController; 
    } 
} 
相關問題