[英]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];
}
目前我infoViewController
由rootViewController
。 但是,如果應用程序不在rootViewController
時進入背景,該rootViewController
辦? 構造看起來像這樣:
當該應用程序位於“另一個頁面”中時,它將進入后台,並且我向我的應用程序發送了一個Notification
。 當我嘗試從通知中打開我的應用程序時。 控制台告訴我:
並且無法提供infoViewController
。 請有人幫助我。
錯誤日志告訴您,您正在嘗試從不在前台的控制器中展示InfoViewController,這是正確的,因為已經展示了另一個控制器。
我對此的解決方案:
然后,當您收到遠程通知時,請執行以下操作:
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.