Starting a background task as Loop in Swift

I know I can create a background job like this:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ // do some task dispatch_async(dispatch_get_main_queue(), ^{ // update some UI }); }); 

( Source )

How to create a background task that executes a code block every n seconds and how can I stop this task?

+5
source share
1 answer

Combine NSTimer and your background code. It will look like this:


Objective-c

 - (void)someBackgroundTask:(NSTimer *)timer { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{ // do some task dispatch_async(dispatch_get_main_queue(), ^{ // update some UI }); }); } 

and then call this method with a timer

 NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(someBackgroundTask:) userInfo:nil repeats:YES]; 

to stop this timer and background execution

 [timer invalidate]; 


Swift 2.2

 func someBackgroundTask(timer:NSTimer) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), { () -> Void in println("do some background task") dispatch_async(dispatch_get_main_queue(), { () -> Void in println("update some UI") }) }) } 

and then call this method with a timer

 var timer = NSTimer(timeInterval: 1.0, target: self, selector: "someBackgroundTask:", userInfo: nil, repeats: true) 

to stop this timer and background execution

 timer.invalidate() 

Swift 3 and later

 func someBackgroundTask(timer:Timer) { DispatchQueue.global(qos: DispatchQoS.background.qosClass).async { print("do some background task") DispatchQueue.main.async { print("update some UI") } } } 

and create / call a timer like

 var timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in self.someBackgroundTask(timer: timer) } 

invalidate method is the same.

+16
source

All Articles