Timeout function after 10 seconds Swift/iOS

喜欢而已 提交于 2020-01-14 13:15:57

问题


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

回答1:


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



回答2:


Here is the solution for Swift 4

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



回答3:


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


来源:https://stackoverflow.com/questions/40167786/timeout-function-after-10-seconds-swift-ios

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!