10秒后超时函数Swift/iOS
Timeout function after 10 seconds Swift/iOS
如果尝试连接 10 秒后登录不成功,我想显示 "Network Error" 消息。
如何在 10 秒后停止登录功能并显示此错误消息?
我正在使用 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)
你也不需要通过计时器来管理它,因为计时器会在 10 秒后准确触发,与你的 API 是否得到响应无关,只需使用超时来管理它。
这是您管理超时的方法
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
这是 Swift 4
的解决方案
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
// Excecute after 3 seconds
}
如果尝试连接 10 秒后登录不成功,我想显示 "Network Error" 消息。
如何在 10 秒后停止登录功能并显示此错误消息?
我正在使用 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)
你也不需要通过计时器来管理它,因为计时器会在 10 秒后准确触发,与你的 API 是否得到响应无关,只需使用超时来管理它。
这是您管理超时的方法
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
这是 Swift 4
的解决方案DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
// Excecute after 3 seconds
}