在 Swift 中创建一个基于超时的函数
Create a function based on timeout in Swift
我想在很长的时间内制作一个 return 的功能。如果超时,函数应该 return 一些预定义的值。例如,
func loginFunc(timeOut: Int) {
Login.getUSerAuthenticaiton(email: "abc@zyf.com", password: "123456789", completion: {_,_ in
print("Reponse")
})
}
像这样调用函数,
loginFunc(timeOut: 10)
意味着,该函数应该 运行 10 秒之后它应该 return 零。确保它将是一个 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
})
}
我想在很长的时间内制作一个 return 的功能。如果超时,函数应该 return 一些预定义的值。例如,
func loginFunc(timeOut: Int) {
Login.getUSerAuthenticaiton(email: "abc@zyf.com", password: "123456789", completion: {_,_ in
print("Reponse")
})
}
像这样调用函数,
loginFunc(timeOut: 10)
意味着,该函数应该 运行 10 秒之后它应该 return 零。确保它将是一个 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
})
}