I want to make a function that returns something within significant time. The function should return some predefined value if timeout. for example,
func loginFunc(timeOut: Int) {
Login.getUSerAuthenticaiton(email: "[email protected]", password: "123456789", completion: {_,_ in
print("Reponse")
})
}
call Function like,
loginFunc(timeOut: 10)
Means, the function should run for 10 seconds after that it should return nil. Make sure it will be an API call or it can be a normal funtion.
First way:
let timer = Timer.scheduledTimer(withTimeInterval: 10, repeats: false) { timer in
print("Time is Over")
}
Login.getUSerAuthenticaiton(email: "[email protected]", password: "123456789", completion: {_,_ in
print("Reponse")
timer.invalidate()
})
You can invalidate timer if a response will faster than 10 sec and timer callback will never fired
Second way:
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: "[email protected]", password: "123456789", completion: {_,_ in
print("Reponse")
isResponseGet = true
})
}