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



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

func loginFunc(timeOut: Int) {

Login.getUSerAuthenticaiton(email: "abc@zyf.com", password: "123456789", completion: {_,_ in 
print("Reponse")
})
}

调用类似函数,

loginFunc(timeOut: 10)

也就是说,函数应该运行10秒,然后返回nil。请确保它将是一个API调用,或者它可以是一个正常的函数。

第一种方式:

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()
})

如果响应速度超过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
})
}

最新更新