Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timeout function after 10 seconds Swift/iOS

Tags:

ios

swift

timeout

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>
}
like image 293
Nishant Roy Avatar asked Oct 21 '16 03:10

Nishant Roy


People also ask

How do I set timeout in Swift?

“settimeout in swift” Code Answer DispatchQueue. main. asyncAfter(deadline: . now() + 2.0) { // Change `2.0` to the desired number of seconds.

How do you call a function after 2 seconds in Swift?

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.

Is there a wait function in Swift?

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.


2 Answers

Here is the solution for Swift 4

DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
   // Excecute after 3 seconds
}
like image 63
Hiran D.A Walawage Avatar answered Oct 27 '22 11:10

Hiran D.A Walawage


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
like image 35
DevB2F Avatar answered Oct 27 '22 11:10

DevB2F