10秒后超时functionSwift / iOS

我想要显示一个“networking错误”消息,如果尝试连接10秒后,login不成功。

如何在10秒后停止loginfunction并显示此错误消息?

我正在使用AlamoFire。

我没有完整的实现,但这是我希望我的函数的行为的骨架:

func loginFunc() { /*Start 10 second timer, if in 10 seconds loginFunc() is still running, break and show NetworkError*/ <authentication code here> } 

如果你使用下面的Alamofire是定义超时的代码

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

你也不需要通过定时器来pipe理它,因为定时器会在10秒后激活,API无论是否得到响应都无关紧要,只需要超时pipe理即可。

这里是你如何pipe理超时

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