So I need to update a UILabel
text value after X seconds have passed after the view appears on screen, the initial label text value comes from an API endpoint which is refreshed everytime the view appears.
Im currently doing the following:
func updateLabelAfterAPICall(initialValue: String) {
lastValue = initialValue //this is a local variable so I can use it to set the text once the view dissappears.
label.text = lastValue
Task {
try? await Task.sleep(nanoseconds: 5_500_000_000)
label.text = "New Value after 5.5 seconds passed"
}
}
Once the view dissappears, I need to set the label back to its initial value so I reset it again in a viewDidDissappear
(if I dont do this, everytime the view is shown I see the "new text" for a brief second until the API call finishes, this is unwanted):
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
label.text = lastValue
}
This seems to be working OK for the most part but I feel like there’s some edge case Im missing where I might need to cancel the Task or something similar? Maybe if I make the view appear and dissappear a bunch of times before 5.5 seconds have passed, would that create a bunch of different Tasks?
I ask this since I cant really replicate it exactly every time, but while testing, I’ve encountered some glitches such as the text not resetting to lastValue
once I return to the view (the majority of times it seems to work fine though, which makes testing and debugging a pain).
Any tip for improvement is welcomed. Thanks!
2
Answers
It may not be safe to put an action you are actively performing to sleep. You can do this on the main thread.
Try this:
It seems you might be concerned about what happens if the view disappears before the label has a chance to change. In that case you’d presumably like to cancel the whole Task operation. To do so, retain the Task in an instance property so that you can cancel it if the view disappears prematurely, something like this:
The bulk of the Task is the call to
Task.sleep
, which is cancellable, so the whole operation will be cancelled in good order because theTask.sleep
call willthrow
when cancelled and the whole Task operation will abort.