Swift/iOS 10 秒后的超时功能
如果尝试连接 10 秒后登录未成功,我想显示网络错误"消息.
I want to display a "Network Error" message if after 10 seconds of trying to connect, a login does not succeed.
如何在 10 秒后停止我的登录功能并显示此错误消息?
How can I stop my login function after 10 seconds and show this error message?
我正在使用 AlamoFire.
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>
}
如果你使用的是Alamofire
下面是定义超时的代码
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)
你也不需要通过定时器来管理它,因为定时器会在 10 秒后触发,不管你的 API 是否得到响应,只需通过超时来管理它.
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.
这是您管理超时的方法
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
}
}
}