How to use background thread in swift?

Anshul picture Anshul · Jun 5, 2014 · Viewed 278.5k times · Source

How to use threading in swift?

dispatchOnMainThread:^{

    NSLog(@"Block Executed On %s", dispatch_queue_get_label(dispatch_get_current_queue()));

}];

Answer

tobiasdm picture tobiasdm · Aug 1, 2014

Swift 3.0+

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

DispatchQueue.global(qos: .background).async {
    print("This is run on the 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_BACKGROUND
let backgroundQueue = dispatch_get_global_queue(qualityOfServiceClass, 0)
dispatch_async(backgroundQueue, {
    print("This is run on the 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_BACKGROUND didn't actually work, instead use Int(QOS_CLASS_BACKGROUND.value).

For more information see Apples documentation