1

Please help me to convert this line to swift 3.0:

dispatch_async(DispatchQueue.global(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0))

And what does it exactly mean? Something like: do the code in brackets in the main queue?

Thanks in advance.

ps. This line of code was taken from apple's code to work with core data

Tung Fam
  • 7,899
  • 4
  • 56
  • 63

2 Answers2

7

In Swift 3 You can write like this

DispatchQueue.global(qos: .background).async {

}

It means what every the code written in between the bracket will perform in the background. and if you want to make any changes in this background thread you have to switch to the main thread. by writing the block below.

dispatch_async(dispatch_get_main_queue()) { 
     // Your code for UI Changes.
}

EDIT: Swift 3

DispatchQueue.main.async {
}
Bhautik Ziniya
  • 1,554
  • 12
  • 19
  • `DispatchQueue.main.async {}` or `DispatchQueue.main.sync {}`. For the main queue. – Zico Sep 17 '16 at 13:21
  • `dispatch_async(DispatchQueue.global(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) ` what about `0` ? how can i set `0` –  Oct 19 '16 at 06:08
2

One of the most common task in Grand Central Dispatch (GDC) pattern is performed work on a global background queue and update the UI on the main queue as soon as the work is done.The new API looks like this:

DispatchQueue.global(attributes: [.qosDefault]).async { 
    // Background thread
    DispatchQueue.main.async(execute: { 
        // UI Updates
    })
}

Queues now take attributes on init. This is a Swift optionSet and can include queue options such as serial vs concurrent, memory and activity management option and the quality of service (.default, .userInteractive, .userInitiated, .utility and .background).

New changes:

  • DISPATCH_QUEUE_PRIORITY_HIGH: -> .userInitiated
  • DISPATCH_QUEUE_PRIORITY_DEFAULT: -> .default
  • DISPATCH_QUEUE_PRIORITY_LOW: -> .utility
  • DISPATCH_QUEUE_PRIORITY_BACKGROUND: -> .background

if you want to learn more about, this is a good talk https://developer.apple.com/videos/play/wwdc2016/720/

Jorge Luis Jiménez
  • 1,203
  • 13
  • 20