在本地通知后呈现UIViewController

时间:2011-05-16 16:19:26

标签: iphone ipad uiviewcontroller uinavigationcontroller uilocalnotification

application:didFinishLaunchingWithOptions:中,我初始化UINavigationController。稍后,我将UINavigationController添加到窗口:

[self.window addSubview:navigationController.view]

一切正常。现在我向我的应用添加了本地通知,当用户响应一个时,我想提出一个UIViewController。所以我认为我可以覆盖application:didReceiveLocalNotification:并在那里使用我的navigationController

[navigationController pushViewController:someVC animated:YES];

然而,这不起作用。我做了一些调试并注意到虽然navigationController不是nil,但navigationController.view没有超级视图,所以我认为它没有显示。

所以,我的问题是:我应该在哪里推动UIViewController以便显示它?

2 个答案:

答案 0 :(得分:5)

在AppDelegate.h中添加:

//Under where you have <UIKit/UIKit.h>
extern NSString *localReceived;

在AppDelegate.m中添加:

//All the way on top where you import your viewControllers
NSString *localReceived = @"localReceived";

- (void)application:(UIApplication *)app didReceiveLocalNotification:(UILocalNotification *)localNotification; 方法的AppDelegate.m中添加以下内容:

        [[NSNotificationCenter defaultCenter] postNotificationName:localReceived object:self];

确保您的viewController是一个navigationController

如果不是,请执行以下操作 - 将此段代码添加到- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

    UINavigationController *nvcontrol = [[UINavigationController alloc] initWithRootViewController:viewController];

[window addSubview:nvcontrol.view];
[window makeKeyAndVisible];

现在 - 在你的viewController.m中将它添加到你的-viewDidLoad函数

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(localAction) name:localReceived object:nil];

创建 - (void)localAction并在该方法中添加您的navigationController代码以推送到下一个View Controller!

希望对你有用。像我的魅力一样工作

答案 1 :(得分:2)

所以这就是另一种采用不同方法的解决方案。它对我来说就像一个魅力。看看:

- (void)application:(UIApplication *)app didReceiveLocalNotification:(UILocalNotification *)localNotification{
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
    CustomViewController *cvc = (CustomViewController *)[storyboard instantiateViewControllerWithIdentifier:@"CustomVC"];
    AnotherViewController *avc = (AnotherViewController *)[storyboard instantiateViewControllerWithIdentifier:@"AnotherVC"];
    avc.someValue = @"Passing a value"; //Optional
    UINavigationController *nav = (UINavigationController *) self.window.rootViewController;
    nav.viewControllers = [NSArray arrayWithObjects:cvc,avc, nil];
    [(UINavigationController *)self.window.rootViewController popToViewController:avc animated:TRUE];
    [[UIApplication sharedApplication] cancelLocalNotification:localNotification]; 
    //Cancel Just for not showing it anymore on the notifications list...
}