簡體   English   中英

Swift / iOS 10秒后超時功能

[英]Timeout function after 10 seconds Swift/iOS

我想顯示“網絡錯誤”消息,如果在嘗試連接10秒后,登錄失敗。

如何在10秒后停止登錄功能並顯示此錯誤消息?

我正在使用AlamoFire。

我沒有完整的實現,但這是我希望我的函數行為的骨架:

func loginFunc() {

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


    <authentication code here>
}
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

如果您使用下面的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
            }
     }
}

這是Swift 4的解決方案

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM