簡體   English   中英

輕按通知時啟動特定的View Controller

[英]Launching a specific View Controller when a notification is tapped

我希望在用戶點擊視圖控制器時顯示一個特定的視圖控制器。 我知道以前針對同一件事發布了很多問題,也有很多答案,但似乎沒有一個對我有用。 這是我的“ AppDelegate”中“ didReceiveRemoteNotification”方法中的代碼

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);

從獲取的日志打印中可以看到,我正在獲取推送中發送的確切數據。 唯一的問題是,在點擊通知時,我試圖呈現/推送的視圖控制器從未被看到。 任何解決方法? 我做錯了什么嗎? 非常感謝您的幫助。

如果您的應用程序在后台運行,則永遠不會調用方法“ 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中,將附加通知有效內容。

我認為是因為didReceiveRemoteNotification:是在后台線程上調用的,並且presentViewController可能需要在主線程上調用。

下面的代碼強制將視圖控制器異步顯示在主線程中Note: a block should never be synchronously run on the main thread 要了解有關Grand Central Dispatch的更多信息,請參見此處

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM