Hi
I need to have a background tack running. This task is to do some calculations about every five minutes and then update the UI. This can be either in a method or in a block of code. After doing a bunch of reading, my guess is this might be done with dispatch_async, but I haven't yet been able to find an example to get through those last few steps. Everything I've seen looks like dispatch_async is in a method call, which causes it to run asynchronously, but then the method goes away once complete. I'd like the method/bock of code to hang around for the life of the app (in the background) and update the UI irrespective of what the rest of the app is doing. Any examples of this would be appreciated. Thanks...
Do something like this:
func runevery(seconds: Double, closure: () -> ()) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(seconds * Double(NSEC_PER_SEC))),
dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0)) {
closure()
runevery(seconds, closure: closure)
}
}
runevery(5) {
print("\n Doing calculations\n")
dispatch_async(dispatch_get_main_queue()) {
print("\n !!! UPDATING UI !!!\n")
}
}
It is important that you do the calculations on the background thread (QOS_CLASS_BACKGROUND), and that you switch to the main thread before updating the UI. Otherwise, your UI will stop working during the calculations.