8

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>
}
Nishant Roy
  • 1,043
  • 4
  • 16
  • 35

3 Answers3

19

Here is the solution for Swift 4

DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
   // Excecute after 3 seconds
}
Hiran Walawage
  • 2,048
  • 1
  • 22
  • 20
4

If you are using Alamofire below is the code to define timeout

let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.timeoutIntervalForRequest = 10 // seconds
configuration.timeoutIntervalForResource = 10
self.alamoFireManager = Alamofire.Manager(configuration: configuration)

also you don't need to manage it through timer, as timer will fire exactly after 10 seconds, irrelevant whether your API get response or not, just manage it with timeout.

and here is how you manage timeout

self.alamofireManager!.request(.POST, "myURL", parameters:params)
.responseJSON { response in
    switch response.result {
        case .Success(let JSON):
            //do json stuff
        case .Failure(let error):
            if error._code == NSURLErrorTimedOut {
               //call your function here for timeout
            }
     }
}
Rajat
  • 10,977
  • 3
  • 38
  • 55
4
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
DevB2F
  • 4,674
  • 4
  • 36
  • 60