Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use background thread in swift?

How to use threading in swift?

dispatchOnMainThread:^{      NSLog(@"Block Executed On %s", dispatch_queue_get_label(dispatch_get_current_queue()));  }]; 
like image 992
Anshul Avatar asked Jun 05 '14 09:06

Anshul


2 Answers

Swift 3.0+

A lot has been modernized in Swift 3.0. Running something on a background queue looks like this:

DispatchQueue.global(qos: .userInitiated).async {     print("This is run on a background queue")      DispatchQueue.main.async {         print("This is run on the main queue, after the previous code in outer block")     } } 

Swift 1.2 through 2.3

let qualityOfServiceClass = QOS_CLASS_USER_INITIATED let backgroundQueue = dispatch_get_global_queue(qualityOfServiceClass, 0) dispatch_async(backgroundQueue, {     print("This is run on a background queue")      dispatch_async(dispatch_get_main_queue(), { () -> Void in         print("This is run on the main queue, after the previous code in outer block")     }) }) 

Pre Swift 1.2 – Known issue

As of Swift 1.1 Apple didn't support the above syntax without some modifications. Passing QOS_CLASS_USER_INITIATED didn't actually work, instead use Int(QOS_CLASS_USER_INITIATED.value).

For more information see Apples documentation

like image 66
tobiasdm Avatar answered Sep 18 '22 21:09

tobiasdm


Dan Beaulieu's answer in swift5 (also working since swift 3.0.1).

Swift 5.0.1

extension DispatchQueue {      static func background(delay: Double = 0.0, background: (()->Void)? = nil, completion: (() -> Void)? = nil) {         DispatchQueue.global(qos: .background).async {             background?()             if let completion = completion {                 DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: {                     completion()                 })             }         }     }  } 

Usage

DispatchQueue.background(delay: 3.0, background: {     // do something in background }, completion: {     // when background job finishes, wait 3 seconds and do something in main thread })  DispatchQueue.background(background: {     // do something in background }, completion:{     // when background job finished, do something in main thread })  DispatchQueue.background(delay: 3.0, completion:{     // do something in main thread after 3 seconds }) 
like image 45
frouo Avatar answered Sep 21 '22 21:09

frouo