I want to display a "Network Error" message if after 10 seconds of trying to connect, a login does not succeed.
How can I stop my login function after 10 seconds and show this error message?
I'm using AlamoFire.
I don't have the full implementation, but this is the skeleton of what I want my function to behave like:
func loginFunc() {
/*Start 10 second timer, if in 10 seconds
loginFunc() is still running, break and show NetworkError*/
<authentication code here>
}
“settimeout in swift” Code Answer DispatchQueue. main. asyncAfter(deadline: . now() + 2.0) { // Change `2.0` to the desired number of seconds.
Execute Code After Delay Using asyncAfter() Sometimes, you might hit the requirement to perform some code execution after a delay, and you can do this by using Swift GCD (Grand Central Dispatch) system to execute some code after a set delay.
Create A Delay and Make a Thread Wait in Swift By using Thread. sleep and DispatchQueue. asyncAfter you can implement delays and use sleep in your Swift code.
Here is the solution for Swift 4
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
// Excecute after 3 seconds
}
func delay(delay:Double, closure:()->()) {
dispatch_after(
dispatch_time( DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), closure)
}
func loginFunc() {
delay(10.0){
//time is up, show network error
//return should break out of the function (not tested)
return
}
//authentication code
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With