10秒后的超时函数 Swift/iOS

8

如果在尝试连接后10秒钟登录失败,我希望显示“网络错误”消息。

如何在10秒钟后停止我的登录功能并显示此错误消息?

我正在使用AlamoFire。

我没有完整的实现,但这是我想让我的函数行为的框架:

func loginFunc() {

    /*Start 10 second timer, if in 10 seconds 
     loginFunc() is still running, break and show NetworkError*/


    <authentication code here>
}

1
请更新您的问题,并附上您希望超时的相关代码。 - rmaddy
已更新函数框架。 - Nishant Roy
请更新您的问题,附上需要添加超时功能的实际工作代码。 - rmaddy
我还没有完整的可用代码。反正完整的代码有什么关系呢?它只是一个调用数据库来检查用户/密码组合是否准确的过程。 - Nishant Roy
有许多种方法可以进行网络调用,因此进行超时操作的能力取决于您正在使用的方式。 - rmaddy
请在您的代码中提到您使用的库,例如 Alamofire 或 AFNetworking 等。 - xmhafiz
3个回答

20

这是 Swift 4 的解决方案

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

4
如果您正在使用 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
            }
     }
}

谢谢Rajat。当函数超时的时候,我该如何调用它?比如说,当AlamoFire超时时,我想调用myFunc() - Nishant Roy
1
已编辑我的答案以处理超时,请检查。 - Rajat
当我只使用 Alamofire 时,我的请求正常工作。但是当我使用 Alamofire.Manager 时,它会显示 NSErrorFailingURLStringKey - Nishant Roy
“init()”解决方案对我无效,因为我的代码中没有任何“init()”调用。有没有办法将配置传递给“Alamofire”本身?而不是传递给管理器? - Nishant Roy
尝试在viewDidLoad中运行它。 - Rajat

4
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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接