从didFinishLaunchingWithOptions

时间:2017-09-13 08:12:01

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

我正在向应用程序发送推送通知,该通知已终止,似乎只触发了此方法。我想在使用推送通知启动应用程序时打开ViewController,但它不会执行任何操作只是打开应用程序。

我尝试使用此代码实现此目的:

if (launchOptions != nil) {

            NSDictionary* userInfo = [launchOptions valueForKey:@"UIApplicationLaunchOptionsRemoteNotificationKey"];
            NSDictionary *apsInfo = [userInfo objectForKey:@"aps"];
            if (apsInfo)
            {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"openNews" object:nil userInfo:userInfo];
            }


}

并试过这个......

if (launchOptions != nil) {

            NSDictionary* userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
            if (userInfo != nil)
            {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"openNews" object:nil userInfo:userInfo];
            }
}

当app通过推送通知终止时,如何启动ViewController的任何想法?

所以我试图将通知信息保存到NSUserDefaults,如果launchOptions!= nil只是为了检查我是否接收到通知信息并且该部分代码被触发,但是由于某种原因这部分不起作用:

[[NSNotificationCenter defaultCenter] postNotificationName:@"openNews" object:nil userInfo:userInfo];

但我使用相同的方法,无处不在,它工作正常

1 个答案:

答案 0 :(得分:3)

这不会起作用,因为你发布的通知没有人抓住它。

嗯,你可以在这里做的是在你收到你指定的launchOptions时设置应用程序的初始ViewController。

您可以使用以下方式进行设置:

self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"YourStoryboard" bundle:nil];
UIViewController *viewController = [storyboard instantiateViewControllerWithIdentifier:@"YourStoryboardId"];

self.window.rootViewController = viewController;
[self.window makeKeyAndVisible];

在设计导航时要小心。特别是如果您希望您的初始ViewController成为具有访问导航堆栈的后退按钮的页面。

由于你将它作为初始视图控制器,如果它尝试popViewController,它将弹出为空。

编辑:

如果您希望延迟从MainVC打开它,您可以将Tnis放入MainVC

[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(openAnotherVC:)
name:@"YourPostNotificationName" object:nil];

然后在 openAnotherVC:方法

中导航到所需的VC