簡體   English   中英

在點擊通知時無法正確顯示ViewController

[英]Can't present ViewController correctly on notification tapped

我正在使用Objective-C 我想呈現一個infoViewController其中包含來自通知的內容。

這是我的代碼:

- (void)application:(UIApplication*)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    [self presentViewControllerWithUserInfo:userInfo];
}


- (void)presentViewControllerWithUserInfo:(NSDictionary *)userInfo {
    infoViewController *vc = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"info"];
    vc.infoString = [[userInfo objectForKey:@"info"] objectForKey:@"string"];

    //NSLog(@"class: %@", [self.window.rootViewController class]);

    [self.window.rootViewController presentViewController:vc animated:YES completion:nil];
}

目前我infoViewControllerrootViewController 但是,如果應用程序不在rootViewController時進入背景,該rootViewController辦? 構造看起來像這樣: 在此處輸入圖片說明

當該應用程序位於“另一個頁面”中時,它將進入后台,並且我向我的應用程序發送了一個Notification 當我嘗試從通知中打開我的應用程序時。 控制台告訴我: 在此處輸入圖片說明

並且無法提供infoViewController 請有人幫助我。

錯誤日志告訴您,您正在嘗試從不在前台的控制器中展示InfoViewController,這是正確的,因為已經展示了另一個控制器。

我對此的解決方案:

  1. 創建一個BaseViewController類(如果尚未創建),該類應從應用程序的所有控制器進行擴展。
  2. 在BaseViewController中創建一個名為CURRENT_CONTROLLER的靜態 UIViewController屬性。
  3. 在viewDidAppear()方法中設置CURRENT_CONTROLLER = self
  4. 如果在任何視圖控制器中重寫此方法,請記住始終調用super.viewDidAppear()。

然后,當您收到遠程通知時,請執行以下操作:

infoViewController *vc = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"info"];
vc.infoString = [[userInfo objectForKey:@"info"] objectForKey:@"string"];

if (BaseViewController.CURRENT_CONTROLLER != nil) {
    [BaseViewController.CURRENT_CONTROLLER presentViewController:vc animated:YES completion:nil];
} else {
    // app just started, your code works well
    // this code could never be executed if you extend BaseViewController from all your view controllers
}

我認為當您退出應用程序時,在單擊通知時未調用didReceiveRemoteNotification方法,而是調用了didFinishLaunchingWithOptions方法,您必須在其中檢查天氣應用程序是否通過通知啟動

將以下代碼放在didFinishLaunchingWithOptions中:

 NSDictionary *launchOptionDict = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    if (launchOptionDict) {
       [self presentViewControllerWithUserInfo:launchOptionDict];
    }

調用方法有些延遲。 嘗試這個。

double delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);

dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
//code to be executed on the main queue after delay
[self presentViewControllerWithUserInfo:userInfo];
});

暫無
暫無

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

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