web-dev-qa-db-ja.com

5秒後にUIAlertViewを閉じますSwift

UIActivityIndi​​catorを含む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()
34
Surge Pedroza

UIAlertViewは、次のようにプログラムで5秒遅れて閉じることができます。

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)
})
42
Lyndsey Scott

Swift 3およびSwift 4(これらの回答の一部に触発されました: [1][2][3] ):

// the alert view
let alert = UIAlertController(title: "", message: "alert disappears after 5 seconds", preferredStyle: .alert)
self.present(alert, animated: true, completion: nil)

// change to desired number of seconds (in this case 5 seconds)
let when = DispatchTime.now() + 5
DispatchQueue.main.asyncAfter(deadline: when){
  // your code with delay
  alert.dismiss(animated: true, completion: nil)
}

結果:

enter image description here

76
ronatory

in 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)
                })
13
George Asda

アラートオブジェクトをグローバル変数として作成します。この目的で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)

}

注:

重要:UIAlertViewはiOS 8では非推奨です(UIAlertViewDelegateも非推奨です。)iOS 8以降でアラートを作成および管理するには、代わりにUIAlertControllerStyleAlertのpreferredStyleでUIAlertControllerを使用します。

参照: IAlertView

6
Midhun MP

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)
})}
5
Vaishnavi

Swiftの場合

let alert = UIAlertController(title: “Alert”, message: “Message”,preferredStyle: UIAlertControllerStyle.alert)
self.present(alert, animated: true, completion: nil)
 DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double((Int64)(5.0 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: {() -> Void in
     alert.dismiss(animated: true, completion: {() -> Void in
 })
})
1
Yakup Ad

私は専門家ではありませんが、これは私のために動作し、私は簡単だと思います

let alert = UIAlertController(title: "", message: "YOUR MESSAGE", preferredStyle: .alert)
present(alert, animated: true) {
   sleep(5)
   alert.dismiss(animated: true)
}
1
user8016538

C#での@ronatoryの回答

var when = new DispatchTime(DispatchTime.Now, 
TimeSpan.FromSeconds(5));
DispatchQueue.MainQueue.DispatchAfter(when, () =>
{
    // your code with delay
    alertController.DismissModalViewController(true);
});
0
jtth

//タイマー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)
        }
    }
}
0
Pratyush Pratik

iOS 8.0 +UIAlertControllerUIViewControllerを継承するため、まさにそれがView Controllerです。したがって、すべての制限が適用されます。そのため、ユーザーがビューを閉じる可能性がある場合、適切なチェックなしにビューを閉じようとするのは完全に安全ではありません。

次のスニペットには、これを実現する方法の例があります。

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)
            }
        }
    }
}
0
Hugo Alonso