【问题标题】:UIAlertController automatically dismisses in iOS 10UIAlertController 在 iOS 10 中自动关闭
【发布时间】:2016-10-24 02:34:25
【问题描述】:

我的AppDelegate 中有一个UIAlertController,并在我收到通知时将其与我的rootViewController 一起呈现。但是当弹出警报视图时,它会迅速关闭自己,而不是等待“确定”按钮上的点击事件......这是我在AppDelegate.m 中的代码。任何的想法?谢谢!

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
    [self showNotification:"Success message here"];
}

- (void)showNotification:(NSString *)text {
    UIAlertController* avc = [UIAlertController alertControllerWithTitle:@"Success" message:text
                                                                      preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *ok = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleCancel handler:nil];
    [avc addAction:ok];
    [self.window.rootViewController presentViewController:avc animated:true completion:nil];
}

编辑:我有另一个视图控制器;称它为 X。X 的viewDidLoad 函数在 X 自行关闭并呈现另一个视图控制器之前有一个倒计时的计时器。我注意到这里有一个有趣的时间问题:当通知来得足够慢,以至于在 X 的计时器到时并呈现另一个视图控制器之后出现 UIAlertController 时,alertController 不会自行关闭。如果发生相反的情况 - 通知来得足够快,使得 UIAlertController 在 X 自行关闭之前出现,那么当计时器到时,整个 AlertController 将被刷新(这是有道理的,我猜......)。我怎样才能防止这种情况发生?

【问题讨论】:

  • 如果解雇是由其他代码引起的,您需要显示该代码。我们需要足够的代码来重现问题(这意味着在我们自己的计算机上发生同样的事情),而您没有提供它。使用 you 显示的代码,警报从不消失。

标签: objective-c ios10 appdelegate uialertcontroller


【解决方案1】:

您可以使用执行选择器方法,如下所示:

- (void)showNotification:(NSString *)text {
  UIAlertController* avc = [UIAlertController alertControllerWithTitle:@"Success" message:text
                                                        preferredStyle:UIAlertControllerStyleAlert];
  UIAlertAction *ok = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleCancel handler:nil];
 [avc addAction:ok];

  [self performSelector:@selector(dissmissAlert:) withObject:avc afterDelay:3.0];

  [self.window.rootViewController presentViewController:avc animated:true completion:nil];
}
-(void)dissmissAlert:(UIAlertController *) alert{
  [alert dismissViewControllerAnimated:true completion:nil];
}

【讨论】:

  • 使用dispatch_after 代替performSelector:withObject:afterDelay: 更清洁、更安全、更通用。
猜你喜欢
  • 2017-08-04
  • 1970-01-01
  • 2017-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-23
  • 1970-01-01
  • 2018-03-03
相关资源
最近更新 更多