简体   繁体   中英

Timeout function after 10 seconds Swift/iOS

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>
}
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 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
            }
     }
}

Here is the solution for Swift 4

DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
   // Excecute after 3 seconds
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM