Swift/iOS 10 秒后的超时功能 [英] Timeout function after 10 seconds Swift/iOS

查看:44
本文介绍了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
            }
     }
}

这篇关于Swift/iOS 10 秒后的超时功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆