点击通知时启动特定的视图控制器

时间:2015-05-30 21:19:45

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

当用户点击视图控制器时,我希望呈现一个特定的视图控制器。我知道之前发布的同一件事有很多问题,但也有很多答案,但似乎没有一个对我有用。这是' didReceiveRemoteNotification'中的代码。我的AppDelegate'

中的方法
if(application.applicationState == UIApplicationStateInactive) {

    NSLog(@"Inactive");

    //Show the view with the content of the push
    if(userInfo)
    {
        NSLog(@"In inactive payload");
        // Create a pointer to the C object
        NSString *cId = [userInfo objectForKey:@"c"];
        NSLog(cId);
        PFObject *targetC = [PFObject objectWithoutDataWithClassName:@"C"   objectId:cId];

        // Fetch C object
        [targetC fetchInBackgroundWithBlock:^(PFObject *object, NSError *error) {
            C *c = [[C alloc] initWithPFObject:object];

            // Show c view controller
            if (!error) {
                NSLog(c.title);

                CDetailsViewController *viewController = [[CDetailsViewController alloc] initWithC:c];
                //[self.navigationController pushViewController:viewController animated:YES];
                [self.navigationController presentViewController:viewController animated:YES completion:nil];
            }
        }];

    }

    handler(UIBackgroundFetchResultNewData);

我正在获取我在推送中发送的确切数据,因为我可以从我得到的日志打印中看到。唯一的问题是,当点击通知时,我试图呈现/推送的视图控制器永远不会被看到。有什么解决方法吗?我做错了什么事?任何帮助都非常感谢。

2 个答案:

答案 0 :(得分:3)

如果您的应用在后台,则永远不会调用“application:didReceiveRemoteNotification:”方法。

您需要在方法中添加:“application:didFinishLaunchingWithOptions:”

 // At the end of the method you force call didNotification:

// Handle any notifications.
if ([launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey]!=nil)
{
    NSDictionary * aPush =[launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    [self application:application didReceiveRemoteNotification:aPush];

}


return YES;
}

如果您的应用由于用户点击通知而启动,则在launchOptions dict中,将附加通知有效内容。

答案 1 :(得分:1)

我假设它是因为在后台线程上调用了 didReceiveRemoteNotification:,并且可能需要在主线程上调用presentViewController。

下面的代码,强制视图控制器以异步方式Note: a block should never be synchronously run on the main thread呈现在主线程中。要了解有关Grand Central Dispatch的更多信息,请参阅here

dispatch_async(dispatch_get_main_queue(), ^
{
    CDetailsViewController *viewController = [[CDetailsViewController alloc] initWithC:c];
    [self.navigationController presentViewController:viewController animated:YES completion:nil];
}