如何在ios中打开现有的viewcontroller

时间:2016-05-09 09:49:54

标签: ios objective-c apple-push-notifications viewcontroller

我需要在接收推送通知时从AppDelegate打开现有的viewcontroller。目前我每次都打开一个新问题所以每次都会调用viewDidLoad并且所有变量都会一次又一次地重新初始化。

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{

[[NSUserDefaults standardUserDefaults] setObject:@"Yes" forKey:@"Got Message"];
            [[NSUserDefaults standardUserDefaults] setObject:userInfo forKey:@"message"];
            [[NSUserDefaults standardUserDefaults]synchronize];            

            HomeViewController* room = [[HomeViewController alloc] init];
            [self.window.rootViewController presentViewController:room
                                                         animated:NO
                                                       completion:nil];



}

3 个答案:

答案 0 :(得分:0)

尝试这样做:

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
    {

    [[NSUserDefaults standardUserDefaults] setObject:@"Yes" forKey:@"Got Message"];
                [[NSUserDefaults standardUserDefaults] setObject:userInfo forKey:@"message"];
                [[NSUserDefaults standardUserDefaults]synchronize];            

                [self.window.rootViewController presentViewController:self.room
                                                             animated:NO
                                                           completion:nil];



    }

    - (UIViewController *)room {
    if (_room == NULL) {
    _room = [[HomeViewController alloc] init];
    }
    return _room;
    }

然后你可以重复使用你的视图控制器(但是,它会暴露你的AppDelegate中的视图控制器,这可能是干净的代码)。

答案 1 :(得分:0)

由于您想使用现有的视图控制器,为什么要使用代码HomeViewController* room = [[HomeViewController alloc] init];

按照你的目标,我的建议是使用属性来保留现有的视图控制器,就像:

@property (strong, nonatomic) UIViewController *existingViewController;

和你

[self.window.rootViewController presentViewController:existingViewController
                                                     animated:NO
                                                   completion:nil];

答案 2 :(得分:0)

您可以在AppDelegate meethod

中获取UINavigationController
UIViewController *yourViewController = //your view controller to show after push
UINavigationController *navController = self.window.rootViewController;
[navController popToViewController:yourViewController animated:YES]
相关问题