在 Swift 中创建一个基于超时的函数

Pat*_*tel 0 timeout function ios swift

我想创建一个在很长的时间内返回某些内容的函数。如果超时,该函数应该返回一些预定义的值。例如,

func loginFunc(timeOut: Int) {
        
    Login.getUSerAuthenticaiton(email: "abc@zyf.com", password: "123456789", completion: {_,_ in 
            print("Reponse")
    })
}
Run Code Online (Sandbox Code Playgroud)

调用函数,例如,

loginFunc(timeOut: 10)
Run Code Online (Sandbox Code Playgroud)

意味着该函数应该运行 10 秒,然后返回 nil。确保它是一个 API 调用或者它可以是一个普通函数。

Ale*_*huk 6

第一种方式:

 let timer = Timer.scheduledTimer(withTimeInterval: 10, repeats: false) { timer in
       print("Time is Over")
    }
    Login.getUSerAuthenticaiton(email: "abc@zyf.com", password: "123456789", completion: {_,_ in
            print("Reponse")
        timer.invalidate()
    })
Run Code Online (Sandbox Code Playgroud)

如果响应速度快于 10 秒并且计时器回调永远不会触发,您可以使计时器无效

第二种方式:

func loginFunc(timeOut: Int) {
    
    var isResponseGet = false
    
    let timer = Timer.scheduledTimer(withTimeInterval: 10, repeats: false) { timer in
        if isResponseGet {
            print("<##>Already get a rtesponse")
        } else {
            print("10 secs left and i didn't get a response")
        }
    }
    Login.getUSerAuthenticaiton(email: "abc@zyf.com", password: "123456789", completion: {_,_ in
            print("Reponse")
        isResponseGet = true
    })
}
Run Code Online (Sandbox Code Playgroud)