Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 5秒后关闭UIAlertView_Ios_Swift_Delay_Uialertview_Uiactivityindicatorview - Fatal编程技术网

Ios 5秒后关闭UIAlertView

Ios 5秒后关闭UIAlertView,ios,swift,delay,uialertview,uiactivityindicatorview,Ios,Swift,Delay,Uialertview,Uiactivityindicatorview,我创建了一个包含UIActivityIndicator的UIAlertView。一切都很好,但我也希望UIAlertView在5秒后消失 如何在5秒后关闭UIAlertView? var alert: UIAlertView = UIAlertView(title: "Loading", message: "Please wait...", delegate: nil, cancelButtonTitle: "Cancel"); var loadingIndicator: UIActivi

我创建了一个包含UIActivityIndicator的UIAlertView。一切都很好,但我也希望UIAlertView在5秒后消失

如何在5秒后关闭UIAlertView?

 var alert: UIAlertView = UIAlertView(title: "Loading", message: "Please wait...", delegate: nil, cancelButtonTitle: "Cancel");

 var loadingIndicator: UIActivityIndicatorView = UIActivityIndicatorView(frame: CGRectMake(50, 10, 37, 37)) as UIActivityIndicatorView
 loadingIndicator.center = self.view.center;
 loadingIndicator.hidesWhenStopped = true
 loadingIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray
 loadingIndicator.startAnimating();

 alert.setValue(loadingIndicator, forKey: "accessoryView")
 loadingIndicator.startAnimating()

 alert.show()

您可以通过编程方式在5秒延迟后关闭
UIAlertView
,如下所示:

alert.show()

// Delay the dismissal by 5 seconds
let delay = 5.0 * Double(NSEC_PER_SEC)
var time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
dispatch_after(time, dispatch_get_main_queue(), {
    alert.dismissWithClickedButtonIndex(-1, animated: true)
})

将警报对象创建为全局变量。 为此,您可以使用
NSTimer

var timer = NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: Selector("dismissAlert"), userInfo: nil, repeats: false)


func dismissAlert()
{
    // Dismiss the alert from here
    alertView.dismissWithClickedButtonIndex(0, animated: true)

}
注意:

重要提示:iOS 8中不推荐使用UIAlertView。(注意 UIAlertViewDelegate也已弃用。)以创建和管理警报 在iOS 8及更高版本中,改用UIAlertController和 UIAlertControllerStyleAlert的首选样式


参考资料:

在swift 2中,您可以这样做。归功于@Lyndsey Scott

 let alertController = UIAlertController(title: "youTitle", message: "YourMessage", preferredStyle: .Alert)
                self.presentViewController(alertController, animated: true, completion: nil)
                let delay = 5.0 * Double(NSEC_PER_SEC)
                let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
                dispatch_after(time, dispatch_get_main_queue(), {
                    alertController.dismissViewControllerAnimated(true, completion: nil)
                })

Swift 3Swift 4中自动解除警报的解决方案(受部分答案启发:,):

结果:

适用于Swift 3


//解除警报w.r.t定时器的通用功能

/** showWithTimer */
public func showWithTimer(message : String?, viewController : UIViewController?) {

    let version : NSString = UIDevice.current.systemVersion as NSString
    if  version.doubleValue >= 8 {
        alert = UIAlertController(title: "", message: message, preferredStyle:.alert)
        viewController?.present(alert ?? UIAlertController(), animated:true, completion:nil)
        let when = DispatchTime.now() + 5
        DispatchQueue.main.asyncAfter(deadline: when){
            self.alert?.dismiss(animated: true, completion: nil)
        }
    }
}

对于swift 4,您可以使用此代码

let alertController = UIAlertController(title:"Alert",message:nil,preferredStyle:.alert)
self.present(alertController,animated:true,completion:{Timer.scheduledTimer(withTimeInterval: 5, repeats:false, block: {_ in
    self.dismiss(animated: true, completion: nil)
})})

我不是专家,但这对我来说很有效,而且我想更容易

let alert = UIAlertController(title: "", message: "YOUR MESSAGE", preferredStyle: .alert)
present(alert, animated: true) {
   sleep(5)
   alert.dismiss(animated: true)
}
@Ronatary的答案是c#


在iOS 8.0+
UIAlertController
中,它继承了
UIViewController
,因此,它只是一个视图控制器。因此,所有的限制都适用。这就是为什么当视图有可能被用户删除时,在没有适当检查的情况下尝试删除它是不完全安全的

在下面的代码片段中,有一个如何实现这一点的示例

func showAutoDismissableAlert(
      title: String?,
      message: String?,
      actions: [MyActionWithPayload], //This is just an struct holding the style, name and the action in case of the user selects that option
      timeout: DispatchTimeInterval?) {

  let alertView = UIAlertController(
      title: title,
      message: message,
      preferredStyle: .alert
  )

  //map and assign your actions from MyActionWithPayload to alert UIAlertAction
  //(..)

  //Present your alert
  //(Here I'm counting on having the following variables passed as arguments, for a safer way to do this, see https://github.com/agilityvision/FFGlobalAlertController) 
  alertView.present(viewController, animated: animated, completion: completion)


  //If a timeout was set, prepare your code to dismiss the alert if it was not dismissed yet
  if let timeout = timeout {
    DispatchQueue.main.asyncAfter(
       deadline: DispatchTime.now() + timeout,
       execute: { [weak alertView] in
            if let alertView = alertView, !alertView.isBeingDismissed {
                alertView.dismiss(animated: true, completion: nil)
            }
        }
    }
}

如果正在加载某些内容,为什么要在固定时间后隐藏警报?你不想在加载完成后隐藏它吗?不需要创建第二个函数。在
dispatch\u after
块中,只需调用
alert.dismissWithClickedButtonIndex(-1,动画:true)
BTW-我喜欢这种方法,而不是使用计时器。@rmaddy它更灵活,但更难看。我可以理解为什么人们会仅仅出于美观的原因而避免使用它。会发生什么呢?警报上有一个ok按钮,并且用户在执行分派之前单击了它?我想知道它是否会崩溃,因为如果用户在5秒延迟之前显示ok按钮,AlertController就会被解除。我试过了,没有收到任何错误消息。所以我想这没问题。在Android上,我制作了一个自动关闭的消息框,用倒计时ok(5),ok(4),…ok(1)更新ok按钮标题。我很想做一些类似的事情,但我不认为我可以与一个alertController。
let alert = UIAlertController(title: "", message: "YOUR MESSAGE", preferredStyle: .alert)
present(alert, animated: true) {
   sleep(5)
   alert.dismiss(animated: true)
}
var when = new DispatchTime(DispatchTime.Now, 
TimeSpan.FromSeconds(5));
DispatchQueue.MainQueue.DispatchAfter(when, () =>
{
    // your code with delay
    alertController.DismissModalViewController(true);
});
func showAutoDismissableAlert(
      title: String?,
      message: String?,
      actions: [MyActionWithPayload], //This is just an struct holding the style, name and the action in case of the user selects that option
      timeout: DispatchTimeInterval?) {

  let alertView = UIAlertController(
      title: title,
      message: message,
      preferredStyle: .alert
  )

  //map and assign your actions from MyActionWithPayload to alert UIAlertAction
  //(..)

  //Present your alert
  //(Here I'm counting on having the following variables passed as arguments, for a safer way to do this, see https://github.com/agilityvision/FFGlobalAlertController) 
  alertView.present(viewController, animated: animated, completion: completion)


  //If a timeout was set, prepare your code to dismiss the alert if it was not dismissed yet
  if let timeout = timeout {
    DispatchQueue.main.asyncAfter(
       deadline: DispatchTime.now() + timeout,
       execute: { [weak alertView] in
            if let alertView = alertView, !alertView.isBeingDismissed {
                alertView.dismiss(animated: true, completion: nil)
            }
        }
    }
}