Can't perform action in background and update progressView in mainThread - ios

I've this method :
func stepThree() {
operation = "prDatas"
let entries = self.data.componentsSeparatedByString("|***|")
total = entries.count
for entry in entries {
++current
dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), {
self.registerDB(entry)
})
}
status.setProgress(Float(current/total), animated: true)
finishAll()
}
I want to perform registerDB function and update my progressBar when complete.
I tested several way but never succeed
EDIT 1
Implementing #Russell proposition, work perfectly, but calculating value inside dispatch_async block always result to 0
Is there an issue about operations and multithread ?
method :
func stepThree() {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
var current = 0
var total = 0
self.operation = "prDatas"
let entries = self.data.componentsSeparatedByString("|***|")
total = entries.count
for entry in entries {
++current
self.registerDB(entry)
dispatch_async(dispatch_get_main_queue(), {
print("value of 'current' is :" + String(current))
print("value of 'total' is :" + String(total))
print("Result is : " + String(Float(current/total)))
self.updateV(Float(current/total))
})
}
})
}
Console output :
value of 'current' is :71
value of 'total' is :1328
Result is : 0.0

Your code will update the status bar immediately - so the job will not have finished.
You need to move the update so that it actually follows the registerDB function, and then you have to make the call on the main thread. Here's an example - using dummy functions instead of your function calls, so that I can ensure it works as expected
func stepThree()
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
let total = 5 // test data for demo
for entry in 0...total
{
// dummy function - just pause
sleep(1)
//self.registerDB(entry)
// make UI update on main queue
dispatch_async(dispatch_get_main_queue(),
{
self.setProgress(Float(entry)/Float(total))
})
}
})
}
func setProgress(progress : Float)
{
progressView.progress = progress
lblProgress.text = String(format: "%0.2f", progress)
}

Related

How to escape (to initial calling place) from a recursive function in swift?

var currentCount = 0
let totalCount = 100
func myEscapingRecursiveFunction(_ json: String, done: #escaping (Bool) -> Void) {
currentCount+=1
if currentCount == totalCount {
done(true)
}
else {
myEscapingRecursiveFunction("xyz") { done in
// what should I do here????
}
}
Calling
// (Initially called here)
myEscapingRecursiveFunction("xyz") { done in
if done {
print("completed") // I want to get response here after the recursion is finished
}
}
I want my function to escape only when the current count is equal to total count, otherwise it should recurse, the problem is that I want to get response in place where it was initially called, but it will always execute the completion handler code where it was last called. here:
You just need to pass the same escaping block to your recurse function.
so call your function like this.
myEscapingRecursiveFunction("xyz", done: done)

UIView fields not update in main thread in Swift

I'm making a download App and to keep the user inform about the progress I use an UIView on top of the main View.
I've got trouble with updating my labels and progressBars.
I try different way to do it like:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
// do some task
dispatch_async(dispatch_get_main_queue()) {
// update some UI
}
}
And also:
self.lblSpeedDownload.setNeedsDisplay()
But it does not update the UI every time it's call
So I tried this https://stackoverflow.com/a/26744884/2410264
For now it's look like it is the best solution I made but it's still not enough quickly update: it's look like the more I call update function, the more it's take time to update UI (1-2-10-20 seconds...)
Here is my code:
A class variable:
let source = dispatch_source_create(DISPATCH_SOURCE_TYPE_DATA_ADD, 0, 0, dispatch_get_main_queue());
Call when I start download:
dispatch_source_set_event_handler(source) {
[unowned self] in
self.updateDownloadView(self.mediaIndex, numberOfMedia: self.numberOfMedia)
}
dispatch_resume(source)
Call when I want to update UI:
dispatch_source_merge_data(source, 1);
And the update function:
func updateDownloadView(mediaIndex : Float, numberOfMedia:Int32){
if downloadPopup != nil {
var tempText:String
if self.selectedDirectories.count == 1 {
tempText = "Folder "
} else {
tempText = "Folders "
}
self.lblFolders.text = tempText + (self.downloadIndex+1).description + "/" + self.selectedDirectories.count.description + " :"
if numberOfMedia == 1 {
tempText = "Image "
} else {
tempText = "Images "
}
self.lblImages.text = tempText + Int(floor(mediaIndex)+1).description + "/" + numberOfMedia.description + " :"
let images_progress = mediaIndex/Float(numberOfMedia)
let folders_progress = Float(self.downloadIndex)+images_progress/Float(self.selectedDirectories.count)
self.progressFolders.setProgress(folders_progress, animated: true)
self.progressImages.setProgress(images_progress, animated: true)
self.lblSpeedDownload.text = Util.getByteString(self.downloadPopup.getDownloadSpeedBySecond())+"/s"
}
}
Do you find something wrong with my code?
Do you have other way to update UI?
Thank you for reading me!

objc_sync_enter / objc_sync_exit not working with DISPATCH_QUEUE_PRIORITY_LOW

I need a read\write lock for my application. I've read https://en.wikipedia.org/wiki/Readers%E2%80%93writer_lock
and wrote my own class, cause there are no read/write lock in swift
class ReadWriteLock {
var logging = true
var b = 0
let r = "vdsbsdbs" // string1 for locking
let g = "VSDBVSDBSDBNSDN" // string2 for locking
func waitAndStartWriting() {
log("wait Writing")
objc_sync_enter(g)
log("enter writing")
}
func finishWriting() {
objc_sync_exit(g)
log("exit writing")
}
// ждет пока все чтение завершится чтобы начать чтение
// и захватить мютекс
func waitAndStartReading() {
log("wait reading")
objc_sync_enter(r)
log("enter reading")
b++
if b == 1 {
objc_sync_enter(g)
log("read lock writing")
}
print("b = \(b)")
objc_sync_exit(r)
}
func finishReading() {
objc_sync_enter(r)
b--
if b == 0 {
objc_sync_exit(g)
log("read unlock writing")
}
print("b = \(b)")
objc_sync_exit(r)
}
private func log(s: String) {
if logging {
print(s)
}
}
}
It works good, until i try to use it from GCD threads.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0)
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
When i try to use this class from different async blocks at some moment it allows to write when write is locked
here is sample log:
wait reading
enter reading
read lock writing
b = 1
wait reading
enter reading
b = 2
wait reading
enter reading
b = 3
wait reading
enter reading
b = 4
wait reading
enter reading
b = 5
wait reading
enter reading
b = 6
wait reading
enter reading
b = 7
wait reading
enter reading
b = 8
wait reading
enter reading
b = 9
b = 8
b = 7
b = 6
b = 5
wait Writing
enter writing
exit writing
wait Writing
enter writing
So, as you can see g was locked, but objc_sync_enter(g) allows to continue.
Why could this happen ?
BTW i checked how many times ReadWriteLock constructed, and it's 1.
Why objc_sync_exit not working and allowing to objc_sync_enter(g) when it's not freed ?
PS Readwirtelock defined as
class UserData {
static let lock = ReadWriteLock()
Thanks.
objc_sync_enter is an extremely low-level primitive, and isn't intended to be used directly. It's an implementation detail of the old #synchronized system in ObjC. Even that is extremely out-dated and should generally be avoided.
Synchronized access in Cocoa is best achieved with GCD queues. For example, this is a common approach that achieves a reader/writer lock (concurrent reading, exclusive writing).
public class UserData {
private let myPropertyQueue = dispatch_queue_create("com.example.mygreatapp.property", DISPATCH_QUEUE_CONCURRENT)
private var _myProperty = "" // Backing storage
public var myProperty: String {
get {
var result = ""
dispatch_sync(myPropertyQueue) {
result = self._myProperty
}
return result
}
set {
dispatch_barrier_async(myPropertyQueue) {
self._myProperty = newValue
}
}
}
}
All your concurrent properties can share a single queue, or you can give each property its own queue. It depends on how much contention you expect (a writer will lock the entire queue).
The "barrier" in "dispatch_barrier_async" means that it is the only thing allowed to run on the queue at that time, so all previous reads will have completed, and all future reads will be prevented until it completes. This scheme means that you can have as many concurrent readers as you want without starving writers (since writers will always be serviced), and writes are never blocking. On reads are blocking, and only if there is actual contention. In the normal, uncontested case, this is extremely very fast.
Are you 100% sure your blocks are actually executing on different threads?
objc_sync_enter() / objc_sync_exit() are guarding you only from object being accessed from different threads. They use a recursive mutex under the hood, so they won't either deadlock or prevent you from repeatedly accessing object from the same thread.
So if you lock in one async block and unlock in another one, the third block executed in-between can have access to the guarded object.
This is one of those very subtle nuances that is easy to miss.
Locks in Swift
You have to really careful what you use as a Lock. In Swift, String is a struct, meaning it's pass-by-value.
Whenever you call objc_sync_enter(g), you are not giving it g, but a copy of g. So each thread is essentially creating its own lock, which in effect, is like having no locking at all.
Use NSObject
Instead of using a String or Int, use a plain NSObject.
let lock = NSObject()
func waitAndStartWriting() {
log("wait Writing")
objc_sync_enter(lock)
log("enter writing")
}
func finishWriting() {
objc_sync_exit(lock)
log("exit writing")
}
That should take care of it!
In addition to #rob-napier's solution. I've updated this to Swift 5.1, added generic typing and a couple of convenient append methods. Note that only methods that access resultArray via get/set or append are thread safe, so I added a concurrent append also for my practical use case where the result data is updated over many result calls from instances of Operation.
public class ConcurrentResultData<E> {
private let resultPropertyQueue = dispatch_queue_concurrent_t.init(label: UUID().uuidString)
private var _resultArray = [E]() // Backing storage
public var resultArray: [E] {
get {
var result = [E]()
resultPropertyQueue.sync {
result = self._resultArray
}
return result
}
set {
resultPropertyQueue.async(group: nil, qos: .default, flags: .barrier) {
self._resultArray = newValue
}
}
}
public func append(element : E) {
resultPropertyQueue.async(group: nil, qos: .default, flags: .barrier) {
self._resultArray.append(element)
}
}
public func appendAll(array : [E]) {
resultPropertyQueue.async(group: nil, qos: .default, flags: .barrier) {
self._resultArray.append(contentsOf: array)
}
}
}
For an example running in a playground add this
//MARK:- helpers
var count:Int = 0
let numberOfOperations = 50
func operationCompleted(d:ConcurrentResultData<Dictionary<AnyHashable, AnyObject>>) {
if count + 1 < numberOfOperations {
count += 1
}
else {
print("All operations complete \(d.resultArray.count)")
print(d.resultArray)
}
}
func runOperationAndAddResult(queue:OperationQueue, result:ConcurrentResultData<Dictionary<AnyHashable, AnyObject>> ) {
queue.addOperation {
let id = UUID().uuidString
print("\(id) running")
let delay:Int = Int(arc4random_uniform(2) + 1)
for _ in 0..<delay {
sleep(1)
}
let dict:[Dictionary<AnyHashable, AnyObject>] = [[ "uuid" : NSString(string: id), "delay" : NSString(string:"\(delay)") ]]
result.appendAll(array:dict)
DispatchQueue.main.async {
print("\(id) complete")
operationCompleted(d:result)
}
}
}
let q = OperationQueue()
let d = ConcurrentResultData<Dictionary<AnyHashable, AnyObject>>()
for _ in 0..<10 {
runOperationAndAddResult(queue: q, result: d)
}
I had the same problem using queues in background. The synchronization is not working all the time in queues with "background" (low) priority.
One fix I found was to use semaphores instead of "obj_sync":
static private var syncSemaphores: [String: DispatchSemaphore] = [:]
static func synced(_ lock: String, closure: () -> ()) {
//get the semaphore or create it
var semaphore = syncSemaphores[lock]
if semaphore == nil {
semaphore = DispatchSemaphore(value: 1)
syncSemaphores[lock] = semaphore
}
//lock semaphore
semaphore!.wait()
//execute closure
closure()
//unlock semaphore
semaphore!.signal()
}
The function idea comes from What is the Swift equivalent to Objective-C's "#synchronized"?, an answer of #bryan-mclemore.

Signal that a network call inside a for-loop is done, then move onto the next item in the for loop?

How would I tell the for-loop to move on to the next item in the array in Swift?
for (key, value) in commentIds {
NetworkHelper.makeNetworkCall(key, completionHandler:{
//Tell current thread the for-loop is being called, to move on to the next item in the for loop?
}
}
I'm planning on having the for-loop in a dispatch_async thread, so it doesn't block the main thread.. Am I designing this wrong..? Should I have a flag?
edit
Flags in the main thread seem to work. Once the network call is done, flip the flag.
I would make the assumption that if the makeNetworkCall method takes a completionHandler parameter that it will be doing its work asynchronously. Given that, the for loop will call makeNetworkCall for every key in commentIds before any of them complete.
If you want to process them in series and not start the next one until the prior has finished, you will need to create an array of the keys and write some code like this:
var commentIdKeys: Array<KeyType>()?
var keyIndex: Int?
func startRequests() {
commentIdKeys = Array(commentIds.keys)
keyIndex = 0
processNextKey()
}
func processNextKey() {
guard let keys = commentIdKeys, let index = keyIndex else {
print("processNextKey() invoked without values set")
return
}
guard keyIndex < keys.count else {
commentIdKeys = nil
keyIndex = nil
print("Finished processing keys")
return
}
NetworkHelper.makeNetworkCall(key, completionHandler:{
// Do some work
self.keyIndex = ++index
self.processNextKey()
}
}

iOS swift while loop freeze my app

I'm developing an app where a user choose his accommodation and pick a time from date picker so the user can know what time the buss will arrive to his accommodation , on the simulator and iPad I'm having the appropriate results however I'm facing this issue on iPhone real device, this is the code :
mTimeString = "5:07 AM"
it will be searched in the array if not found , minus seconds until it matches results in the array . but while loop is freezing my app , i tried to surround it by :
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT ,0)
dispatch_async(queue){}
its not freezing anymore but the I'm not getting the results according to the array
if(defaults.stringForKey(accommodationChoiceKey)?.toInt() == 40) {
var array = ["12:05 AM","12:25 AM","12:45 AM","1:05 AM","1:25 AM","1:45 AM","2:05 AM","2:25 AM","2:45 AM","3:05 AM","3:25 AM","3:45 AM","4:05 AM","4:25 AM","4:45 AM","5:05 AM","5:25 AM","5:45 AM","6:05 AM","6:25 AM","6:45 AM","7:05 AM","7:25 AM","7:45 AM","8:05 AM","8:25 AM","8:45 AM","9:05 AM","9:25 AM","9:45 AM","10:05 AM","10:25 AM","10:45 AM","11:05 AM","11:25 AM","11:45 AM","12:05 PM","12:25 PM","12:45 PM","1:05 PM","1:25 PM","1:45 PM","2:05 PM","2:25 PM","2:45 PM","3:05 PM","3:25 PM","3:45 PM","4:05 PM","4:25 PM","4:45 PM","5:05 PM","5:25 PM","5:45 PM","6:05 PM","6:25 PM","6:45 PM","7:05 PM","7:25 PM","7:45 PM","8:05 PM","8:25 PM","8:45 PM","9:05 PM","9:25 PM","9:45 PM","10:05 PM","10:25 PM","10:45 PM","11:05 PM","11:25 PM","11:45 PM"]
while (find(array, mTimeString) == nil) {
choiceToSeconds--
var newmTime = x.dateByAddingTimeInterval(Double(choiceToSeconds))
var mTimeString = dateFormatter.stringFromDate(newmTime)
if (find(array, mTimeString) != nil) {
transportationLabel.text = mTimeString
break
}
getReady(newmTime)
}
}
You are calculating on Background thread which is okay , but you should NEVER update UI element from background thread ( transportationLabel.text = mTimeString ) , this should be done from main Thread , for example
let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
dispatch_async(dispatch_get_global_queue(priority, 0)) {
if(defaults.stringForKey(accommodationChoiceKey)?.toInt() == 40) {
var array = ["12:05 AM","12:25 AM","12:45 AM","1:05 AM","1:25 AM","1:45 AM","2:05 AM","2:25 AM","2:45 AM","3:05 AM","3:25 AM","3:45 AM","4:05 AM","4:25 AM","4:45 AM","5:05 AM","5:25 AM","5:45 AM","6:05 AM","6:25 AM","6:45 AM","7:05 AM","7:25 AM","7:45 AM","8:05 AM","8:25 AM","8:45 AM","9:05 AM","9:25 AM","9:45 AM","10:05 AM","10:25 AM","10:45 AM","11:05 AM","11:25 AM","11:45 AM","12:05 PM","12:25 PM","12:45 PM","1:05 PM","1:25 PM","1:45 PM","2:05 PM","2:25 PM","2:45 PM","3:05 PM","3:25 PM","3:45 PM","4:05 PM","4:25 PM","4:45 PM","5:05 PM","5:25 PM","5:45 PM","6:05 PM","6:25 PM","6:45 PM","7:05 PM","7:25 PM","7:45 PM","8:05 PM","8:25 PM","8:45 PM","9:05 PM","9:25 PM","9:45 PM","10:05 PM","10:25 PM","10:45 PM","11:05 PM","11:25 PM","11:45 PM"]
while (find(array, mTimeString) == nil) {
choiceToSeconds--
var newmTime = x.dateByAddingTimeInterval(Double(choiceToSeconds))
var mTimeString = dateFormatter.stringFromDate(newmTime)
if (find(array, mTimeString) != nil) {
// This should be done on Main Thread
dispatch_async(dispatch_get_main_queue()) {
transportationLabel.text = mTimeString
}
break
}
getReady(newmTime)
}
}
}
Try replacing
transportationLabel.text = mTimeString
by
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
transportationLabel.text = mTimeString
}];
UI operations must be executed from main thread
EDIT:
In Swift:
NSOperationQueue.mainQueue().addOperationWithBlock({
transportationLabel.text = mTimeString
})

Resources