Queues and Swift 3 issue [duplicate] - ios

This question already has answers here:
How do I dispatch_sync, dispatch_async, dispatch_after, etc in Swift 3, Swift 4, and beyond?
(6 answers)
Closed 6 years ago.
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

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 {
}

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/

Related

GCD stop with cancellable_dispatch_after [duplicate]

This question already has answers here:
Stop a DispatchQueue that is running on the main thread
(2 answers)
Closed 4 years ago.
Grand Central Dispatch (GCD) function they can utilize but once it's set up, these calls can not be easily cancelled.
How could we stop it such as a custom method "cancellable_dispatch_after"
If you are trying to find a way to cancel asynchronous operations using GCD, you should use DispatchWorkItem. It allows you to do the following:
import Dispatch
let task = DispatchWorkItem {
//Do some stuff
}
DispatchQueue.main.async(execute: task)
task.cancel()
Obviously, you wouldn't do this exactly, but I believe it shows how to do what you want.
Hope this helps!

asynchronous Swift function taking long time to update label [duplicate]

I'm beginner swift developer. I'm stucked with this weather app.I'm downloading website data and then displaying in my label.
Unfortunately this whole process takes like 10 second to update my label.
This is probably not because of the network connection as the console is updated instantly.
Thanks for suggestions.
What happens is that code is probably run on a secondary thread. Any UI changes you make should be made on the main thread. So try this:
dispatch_async(dispatch_get_main_queue()) {
// update label
}
This should update your label instantly.
Previously, we would choose the dispatch method (sync vs async) and then the queue we wanted to dispatch our task to. The updated GCD reverses this order - we first choose the queue and then apply a dispatch method.
Swift 3:
Now in Swift 3 the GCD library was updated like in the following way:
DispatchQueue.main.async(execute: {
// UI Updates
})
I hope this help you.
It might be late to answer but in Swift 3 logic should be like this.
DispatchQueue.global(qos: .background).async {
// Background Thread Or Service call Or DB fetch etc
DispatchQueue.main.async {
// Run UI Updates and other logic
}}
Your code has multiple issues.
FIRST: It has strong reference cycle
Fix it by putting this in closure.
[weak weakSelf = self]
SECOND: Update UI in main thread
DispatchQueue.main.async {
//Update UI
weakSelf?.mReslut.text = ""
}

Creating ASYNC task in Swift 2

I want to show users current location in map and I know it's not instantaneous task. I want to call my showCurrentLocation() function in the ASYNC task. I was trying to learn call back closures but i could not understand how can I create ASYNC task for this. I know this is not a best question template for stackoverflow but I don't know how can I ask differently.
Thank you for any help.
Have a nice coding.
In the past I've made a class called AsyncTask for usage purposes like the one you described here.
Lately I've updated it for swift 3
It has 2 generic types:
BGParam - the type of the parameter sent to the task upon execution.
BGResult - the type of the result of the background computation.
If one of them(or both) isn't needed you can set it to Optional or just ignore.
In code example I refer the functions showCurrentLocation() & getCurrentLocation() that you mentioned in OP & comments.
BGParam is set to Int & BGResults is set to CLLocationCoordinate2D
AsyncTask(backgroundTask: {(param:Int)->CLLocationCoordinate2D in
print(param);//prints the Int value passed from .execute(1)
return self.getCurrentLocation();//the function you mentioned in comment
}, afterTask: {(coords)in
//use latitude & longitude at UI-Main thread
print("latitude: \(coords.latitude)");
print("latitude: \(coords.longitude)");
self.showCurrentLocation(coords);//function you mentioned in OP
}).execute(1);//pass Int value 1 to backgroundTask
There is a technology called GCD (Grand Central Dispatch) which you can use to perform such tasks.
let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
dispatch_async(dispatch_get_global_queue(priority, 0)) {
// do some task
dispatch_async(dispatch_get_main_queue()) {
// update some UI
}
}

Updating label takes too long (swift)

I'm beginner swift developer. I'm stucked with this weather app.I'm downloading website data and then displaying in my label.
Unfortunately this whole process takes like 10 second to update my label.
This is probably not because of the network connection as the console is updated instantly.
Thanks for suggestions.
What happens is that code is probably run on a secondary thread. Any UI changes you make should be made on the main thread. So try this:
dispatch_async(dispatch_get_main_queue()) {
// update label
}
This should update your label instantly.
Previously, we would choose the dispatch method (sync vs async) and then the queue we wanted to dispatch our task to. The updated GCD reverses this order - we first choose the queue and then apply a dispatch method.
Swift 3:
Now in Swift 3 the GCD library was updated like in the following way:
DispatchQueue.main.async(execute: {
// UI Updates
})
I hope this help you.
It might be late to answer but in Swift 3 logic should be like this.
DispatchQueue.global(qos: .background).async {
// Background Thread Or Service call Or DB fetch etc
DispatchQueue.main.async {
// Run UI Updates and other logic
}}
Your code has multiple issues.
FIRST: It has strong reference cycle
Fix it by putting this in closure.
[weak weakSelf = self]
SECOND: Update UI in main thread
DispatchQueue.main.async {
//Update UI
weakSelf?.mReslut.text = ""
}

How to do multithreading, concurrency or parallelism in iOS Swift?

Is there any way to create a worker thread in Swift?, for example, if there's a major functionality that requires a lot of calculations and hence causes the main thread to delay for a few seconds, if I would like to move that functionality to a separate thread or a thread that do not block the main thread is there any way to do it with Swift?
I've gone through the basic and advanced components of the Apple Documentation for Swift but there's nothing about concurrency or parallelism, do anyone know something about how to do it(if possible)?
Or you can use operation queues, too. In Swift 3:
let queue = OperationQueue()
queue.addOperation() {
// do something in the background
OperationQueue.main.addOperation() {
// when done, update your UI and/or model on the main queue
}
}
Either this, or GCD, which Andy illustrated, work fine.
See Apple's Concurrency Programming Guide for the relative merits of operation queues and dispatch queues (aka Grand Central Dispatch, GCD). While that guide is still illustrating the examples using Objective-C, the API and concepts are basically the same in Swift (just use the Swift syntax). The documentation for GCD and operation queues in Xcode describes both Objective-C and Swift APIs.
By the way, you'll notice that in both the above example as well as Andy's GCD demonstration, we used "trailing closures". For example, if you look at the definition addOperationWithBlock, that is defined as a function with one parameter which is a "closure" (which is analogous to a block in Objective-C):
func addOperation(_ block: #escaping () -> Swift.Void)
That might lead you to assume that you would invoke it as follows:
queue.addOperation({
// do something in the background
})
But when the last parameter of a function is a closure, the trailing closure syntax allows you to take that final closure parameter out of the parentheses of the function, and move it after the function, yielding:
queue.addOperation() {
// do something in the background
}
And because there's nothing left in the parentheses, you can even go one step further, and remove those empty parentheses:
queue.addOperation {
// do something in the background
}
Hopefully that illustrates how to interpret the NSOperationQueue/OperationQueue and/or GCD function declarations and use them in your code.
You can use Grand Central Dispatch (GCD) for such tasks.
This is a basic example:
let backgroundQueue: dispatch_queue_t = dispatch_queue_create("com.a.identifier", DISPATCH_QUEUE_CONCURRENT)
// can be called as often as needed
dispatch_async(backgroundQueue) {
// do calculations
}
// release queue when you are done with all the work
dispatch_release(backgroundQueue)
This library lets you describe concurrency in a super expressive way:
func handleError(_ error) { ... }
HoneyBee.start(on: DispatchQueue.main) { root in
root.setErrorHandler(handleError)
.chain(function1) // runs on main queue
.setBlockPerformer(DispatchQueue.global())
.chain(function2) // runs on background queue
.branch { stem in
stem.chain(func3) // runs in parallel with func4
+
stem.chain(func4) // runs in parallel with func3
}
.chain(func5) // runs after func3 and func4 have finished
.setBlockPerformer(DispatchQueue.main)
.chain(updateUIFunc)
}
Here is the best resource to learn in detail about
Councurrency

Resources