Swift - Dispatch Queues and the U/I running serially - swift

I have a secondary LaunchScreenViewController for an App that has some animation whilst it gathers three types of background data.
Everything works but the order in which the DispatchQueues.async are run is random. However if I change them to DispatchQueues.sync everything happens in the right order but runs so fast (even with sleeps) you don't see the animations.
This needs to be .sync but how do I control the U/I so that I can see the animation? (Shown here as, e.g. self.subLogo1View.isHidden = true)
Here's the code:
// Queuing Variables
var semaphore = DispatchSemaphore(value: 1)
var semaphoreSub = DispatchSemaphore(value: 1)
override func viewDidLoad() {
super.viewDidLoad()
DispatchQueue.global().async {
self.semaphore.wait()
self.gatherData()
self.semaphore.signal()
}
DispatchQueue.global().async {
self.semaphore.wait()
self.checkNetworkAvailability()
self.semaphore.signal()
}
DispatchQueue.global().async {
self.semaphore.wait()
self.checkSomething()
self.semaphore.signal()
}
}
func gatherData() {
DispatchQueue.main.async {
self.semaphoreSub.wait()
print ("1")
self.subLogo1View.isHidden = true
self.subLogo1View.setNeedsDisplay()
self.semaphoreSub.signal()
}
}
func checkNetworkAvailability() {
DispatchQueue.main.async {
self.semaphoreSub.wait()
print ("2")
self.subLogo2View.isHidden = true
self.subLogo2View.setNeedsDisplay()
self.semaphoreSub.signal()
}
}
func checkSomething() {
DispatchQueue.main.async {
self.semaphoreSub.wait()
print ("3")
self.subLogo3View.isHidden = true
self.subLogo3View.setNeedsDisplay()
self.semaphoreSub.signal()
}
}

Instead of manually serializing your closures with a bunch of semaphores, you maybe better use a custom serial queue. For animation, user UIView.animate
Something like this:
func gatherData() {
DispatchQueue.main.async { // or sync, depending on your animation needs
print ("1: gather Data")
UIView.animate(withDuration: 0.5) {
self.subLogo1View.alpha = 0 // instead of isHidden
}
}
}
func viewDidLoad() {
var mySerialQueue = DispatchQueue (label:"my.serial")
mySerialQueue.async {
self.gatherData()
}
mySerialQueue.async {
self.checkNetworkAvailability()
}
// ...
}

Related

Dispatchqueue and SVProgressHUD in swift

I have been designing an app that analyzes lines of text, and I want to use SVProgressHUD to show progress of it.
This is my code:
let total = text.count
for line in text{
count = count + 1
DispatchQueue.global(pos: .background).async{
//Analyzing line
DispatchQueue.main.async{
SVProgressHUD.showProgress(count/total)
}
}
}
The analyzing works, and the HUD shows properly, when the count reaches total, the process gets stuck, and SVProgressHUD stops at max status, and the program stops. What is the issue with the program?
Am I using Dispatchqueue wrong?
Do I have to call something other to free the background process or something?
I have tried exchanging //Analyzing line and SVProgressHUD.show..., but it still doesn't work. I initially used SVProgress within the loop without the dispatchqueue, but then the progress hud moves only after the analyzation(full loop) has been completed, which is a problem.
Any help would be appreciated.
Thank you.
Try using this code. It does not use loop but implements recursive calls to a function for processing your string data.
func processLines() {
SVProgressHUD.showProgress(0)
// sample data
var text = Array("abcdefghijklmnop")
var lines : [Line] = []
let count : [Int] = Array(0..<text.count)
count.forEach({ pos in lines.append(Line(char: text[pos])) })
var currentIndex : Int = 0
func processLine(at index: Int) {
DispatchQueue.global(qos: .background).async{
//Analyzing line
let line = lines[index]
print("Processing Line CHAR: \(line.char)")
DispatchQueue.main.async{
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
guard currentIndex < lines.count-1 else {
SVProgressHUD.showProgress(1)
return
}
currentIndex += 1
startLineProces(at: currentIndex)
}
}
}
}
func startLineProces(at index: Int) {
processLine(at: index)
SVProgressHUD.showProgress(Float(index) / Float(lines.count))
}
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
startLineProces(at: currentIndex)
}
}
struct Line {
var char: Character
init(char: Character) {
self.char = char
}
}
Use the below string extension to analyse your string. It has a completion block which will return progress as well as status of completion.
extension String {
func analyseString(completion: #escaping (Bool, Float) -> ()) {
let totalCountOfString = self.count
for (index, _) in self.enumerated() {
if index == totalCountOfString - 1 {
completion(true, Float(index)/Float(totalCountOfString))
} else {
completion(false, Float(index)/Float(totalCountOfString))
}
}
}
}
You can call the above method to show your progress as below (maybe on a button click). self.yourString is your input string that you need to analyse.
#IBAction func clicked(_ sender: UIButton) {
DispatchQueue.main.async {
self.yourString.analyseString { (isCompleted, progress) in
if isCompleted {
SVProgressHUD.dismiss()
print("Ending")
} else {
SVProgressHUD.showProgress(progress, status: "Analysing (\(progress)%)")
}
}
}
}

How to showing line one by one in async code?

I want to do for-loop code with async. For simulating the async, I added some delays.
import Cocoa
class ViewController: NSViewController {
private let semaphore = DispatchSemaphore(value: 0)
private let concurrentQueue = DispatchQueue.global()
override func viewDidLoad() {
super.viewDidLoad()
for i in 1...10 {
if run(i) {
break
}
}
}
func run(_ i:Int) -> Bool{
let seed = arc4random()
let isSuccess = seed % 5 == 1
let delayInSeconds = Int(seed % 3)
concurrentQueue.asyncAfter(wallDeadline: .now() + .seconds(delayInSeconds)) {
DispatchQueue.main.async {
self.textView.string += "\(i)\t\(seed)\n"
}
self.semaphore.signal()
}
semaphore.wait()
return isSuccess
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
#IBOutlet var textView: NSTextView!
}
The problem is, when the code runs, all lines were added at once. I want it added one by one. Any idea?
The problem is solved. The reason that update UI part doesn't work is because that func run() is running on main thread, which is blocked by semaphore.wait() always. So to solve the problem, just added it to another thread.
override func viewDidLoad() {
super.viewDidLoad()
concurrentQueue.async {
for i in 1...10 {
if self.run(i) {
break
}
}
}
}

Swift: determinate NSProgressIndicator, async refreshing and waiting for return

Working in Swift3; I've got a pretty expensive operation running in a loop iterating through stuff and building it into an array that on return would be used as the content for an NSTableView.
I wanted a modal sheet showing progress for this so people don't think the app is frozen. By googling, looking around in here and not a small amount of trial and error I've managed to implement my progressbar and have it show progress adequately as the loop progresses.
The problem right now? Even though the sheet (implemented as an NSAlert, the progress bar is in the accesory view) works exactly as expected, the whole thing returns before the loop is finished.
Here's the code, hoping somebody can tell me what am I doing wrong:
class ProgressBar: NSAlert {
var progressBar = NSProgressIndicator()
var totalItems: Double = 0
var countItems: Double = 0
override init() {
progressBar.isIndeterminate = false
progressBar.style = .barStyle
super.init()
self.messageText = ""
self.informativeText = "Loading..."
self.accessoryView = NSView(frame: NSRect(x:0, y:0, width: 290, height: 16))
self.accessoryView?.addSubview(progressBar)
self.layout()
self.accessoryView?.setFrameOrigin(NSPoint(x:(self.accessoryView?.frame)!.minX,y:self.window.frame.maxY))
self.addButton(withTitle: "")
progressBar.sizeToFit()
progressBar.setFrameSize(NSSize(width:290, height: 16))
progressBar.usesThreadedAnimation = true
self.beginSheetModal(for: ControllersRef.sharedInstance.thePrefPane!.mainCustomView.window!, completionHandler: nil)
}
}
static var allUTIs: [SWDAContentItem] = {
var wrappedUtis: [SWDAContentItem] = []
let utis = LSWrappers.UTType.copyAllUTIs()
let a = ProgressBar()
a.totalItems = Double(utis.keys.count)
a.progressBar.maxValue = a.totalItems
DispatchQueue.global(qos: .default).async {
for uti in Array(utis.keys) {
a.countItems += 1.0
wrappedUtis.append(SWDAContentItem(type:SWDAContentType(rawValue: "UTI")!, uti))
Thread.sleep(forTimeInterval:0.0001)
DispatchQueue.main.async {
a.progressBar.doubleValue = a.countItems
if (a.countItems >= a.totalItems && a.totalItems != 0) {
ControllersRef.sharedInstance.thePrefPane!.mainCustomView.window?.endSheet(a.window)
}
}
}
}
Swift.print("We'll return now...")
return wrappedUtis // This returns before the loop is finished.
}()
In short, you're returning wrappedUtis before the asynchronous code has had a chance to finish. You cannot have the initialization closure return a value if the update process itself is happening asynchronously.
You clearly successfully diagnosed a performance problem in the initialization of allUTIs, and while doing this asynchronously is prudent, you shouldn't be doing that in that initialization block of the allUTIs property. Move this code that initiates the update of allUTIs into a separate function.
Looking at ProgressBar, it's really an alert, so I'd call it ProgressAlert to make that clear, but expose the necessary methods to update the NSProgressIndicator within that alert:
class ProgressAlert: NSAlert {
private let progressBar = NSProgressIndicator()
override init() {
super.init()
messageText = ""
informativeText = "Loading..."
accessoryView = NSView(frame: NSRect(x:0, y:0, width: 290, height: 16))
accessoryView?.addSubview(progressBar)
self.layout()
accessoryView?.setFrameOrigin(NSPoint(x:(self.accessoryView?.frame)!.minX,y:self.window.frame.maxY))
addButton(withTitle: "")
progressBar.isIndeterminate = false
progressBar.style = .barStyle
progressBar.sizeToFit()
progressBar.setFrameSize(NSSize(width:290, height: 16))
progressBar.usesThreadedAnimation = true
}
/// Increment progress bar in this alert.
func increment(by value: Double) {
progressBar.increment(by: value)
}
/// Set/get `maxValue` for the progress bar in this alert
var maxValue: Double {
get {
return progressBar.maxValue
}
set {
progressBar.maxValue = newValue
}
}
}
Note, this doesn't present the UI. That's the job of whomever presented it.
Then, rather than initiating this asynchronous population in the initialization closure (because initialization should always be synchronous), create a separate routine to populate it:
var allUTIs: [SWDAContentItem]?
private func populateAllUTIs(in window: NSWindow, completionHandler: #escaping () -> Void) {
let progressAlert = ProgressAlert()
progressAlert.beginSheetModal(for: window, completionHandler: nil)
var wrappedUtis = [SWDAContentItem]()
let utis = LSWrappers.UTType.copyAllUTIs()
progressAlert.maxValue = Double(utis.keys.count)
DispatchQueue.global(qos: .default).async {
for uti in Array(utis.keys) {
wrappedUtis.append(SWDAContentItem(type:SWDAContentType(rawValue: "UTI")!, uti))
DispatchQueue.main.async { [weak progressAlert] in
progressAlert?.increment(by: 1)
}
}
DispatchQueue.main.async { [weak self, weak window] in
self?.allUTIs = wrappedUtis
window?.endSheet(progressAlert.window)
completionHandler()
}
}
}
Now, you declared allUTIs to be static, so you can tweak the above to do that, too, but it seems like it's more appropriate to make it an instance variable.
Anyway, you can then populate that array with something like:
populateAllUTIs(in: view.window!) {
// do something
print("done")
}
Below, you said:
In practice, this means allUTIs is only actually initiated when the appropriate TabViewItem is selected for the first time (which is why I initialize it with a closure like that). So, I'm not really sure how to refactor this, or where should I move the actual initialization. Please keep in mind that I'm pretty much a newbie; this is my first Swift (also Cocoa) project, and I've been learning both for a couple of weeks.
If you want to instantiate this when the tab is selected, then hook into the child view controllers viewDidLoad. Or you can do it in the tab view controller's tab​View(_:​did​Select:​)
But if the population of allUTIs is so slow, are you sure you want to do this lazily? Why not trigger this instantiation sooner, so that there's less likely to be a delay when the user selects that tab. In that case, you might trigger it the tab view controller's own viewDidLoad, so that the tab that needs those UTIs is more likely to have them.
So, if I were considering a more radical redesign, I might first change my model object to further isolate its update process from any specific UI, but rather to simply return (and update) a Progress object.
class Model {
var allUTIs: [SWDAContentItem]?
func startUTIRetrieval(completionHandler: (() -> Void)? = nil) -> Progress {
var wrappedUtis = [SWDAContentItem]()
let utis = LSWrappers.UTType.copyAllUTIs()
let progress = Progress(totalUnitCount: Int64(utis.keys.count))
DispatchQueue.global(qos: .default).async {
for uti in Array(utis.keys) {
wrappedUtis.append(SWDAContentItem(type:SWDAContentType(rawValue: "UTI")!, uti))
DispatchQueue.main.async {
progress.completedUnitCount += 1
}
}
DispatchQueue.main.async { [weak self] in
self?.allUTIs = wrappedUtis
completionHandler?()
}
}
return progress
}
}
Then, I might have the tab bar controller instantiate this and share the progress with whatever view controller needed it:
class TabViewController: NSTabViewController {
var model: Model!
var progress: Progress?
override func viewDidLoad() {
super.viewDidLoad()
model = Model()
progress = model.startUTIRetrieval()
tabView.delegate = self
}
override func tabView(_ tabView: NSTabView, didSelect tabViewItem: NSTabViewItem?) {
super.tabView(tabView, didSelect: tabViewItem)
if let item = tabViewItem, let controller = childViewControllers[tabView.indexOfTabViewItem(item)] as? ViewController {
controller.progress = progress
}
}
}
Then the view controller could observe this Progress object, to figure out whether it needs to update its UI to reflect this:
class ViewController: NSViewController {
weak var progress: Progress? { didSet { startObserving() } }
weak var progressAlert: ProgressAlert?
private var observerContext = 0
private func startObserving() {
guard let progress = progress, progress.completedUnitCount < progress.totalUnitCount else { return }
let alert = ProgressAlert()
alert.beginSheetModal(for: view.window!)
progressAlert = alert
progress.addObserver(self, forKeyPath: "fractionCompleted", context: &observerContext)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
guard let progress = object as? Progress, context == &observerContext else {
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
return
}
dispatchPrecondition(condition: .onQueue(.main))
if progress.completedUnitCount < progress.totalUnitCount {
progressAlert?.doubleValue = progress.fractionCompleted * 100
} else {
progress.removeObserver(self, forKeyPath: "fractionCompleted")
view.window?.endSheet(progressAlert!.window)
}
}
deinit {
progress?.removeObserver(self, forKeyPath: "fractionCompleted")
}
}
And, in this case, the ProgressAlert only would worry about doubleValue:
class ProgressAlert: NSAlert {
private let progressBar = NSProgressIndicator()
override init() {
super.init()
messageText = ""
informativeText = "Loading..."
accessoryView = NSView(frame: NSRect(x:0, y:0, width: 290, height: 16))
accessoryView?.addSubview(progressBar)
self.layout()
accessoryView?.setFrameOrigin(NSPoint(x:(self.accessoryView?.frame)!.minX,y:self.window.frame.maxY))
addButton(withTitle: "")
progressBar.isIndeterminate = false
progressBar.style = .barStyle
progressBar.sizeToFit()
progressBar.setFrameSize(NSSize(width: 290, height: 16))
progressBar.usesThreadedAnimation = true
}
/// Set/get `maxValue` for the progress bar in this alert
var doubleValue: Double {
get {
return progressBar.doubleValue
}
set {
progressBar.doubleValue = newValue
}
}
}
I must note, though, that if these UTIs are only needed for that one tab, it raises the question as to whether you should be using a NSAlert based UI at all. The alert blocks the whole window, and you may want to block interaction with only that one tab.

Check if on correct dispatch queue in Swift 3

I have a few unit tests in which I'd like to test if a callback is called on the correct dispatch queue.
In Swift 2, I compared the label of the current queue to my test queue. However in Swift 3 the DISPATCH_CURRENT_QUEUE_LABEL constant no longer exists.
I did find the dispatch_assert_queue function. Which seems to be what I need, but I'm not sure how to call it.
My Swift 2 code:
let testQueueLabel = "com.example.my-test-queue"
let testQueue = dispatch_queue_create(testQueueLabel, nil)
let currentQueueLabel = String(UTF8String: dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL))!
XCTAssertEqual(currentQueueLabel, testQueueLabel, "callback should be called on specified queue")
Update:
I got confused by the lack of autocomplete, but it is possible to use __dispatch_assert_queue:
if #available(iOS 10.0, *) {
__dispatch_assert_queue(test1Queue)
}
While this does work for unit tests, it annoyingly stops the whole process with a EXC_BAD_INSTRUCTION instead of only failing a test.
Use dispatchPrecondition(.onQueue(expectedQueue)), the Swift 3 API replacement for the dispatch_assert_queue() C API.
This was covered in the WWDC 2016 GCD session (21:00, Slide 128):
https://developer.apple.com/videos/play/wwdc2016/720/
Answering my own question:
Based on KFDoom's comments, I'm now using setSpecific and getSpecific.
This creates a key, sets it on the test queue, and later on, gets it again:
let testQueueLabel = "com.example.my-test-queue"
let testQueue = DispatchQueue(label: testQueueLabel, attributes: [])
let testQueueKey = DispatchSpecificKey<Void>()
testQueue.setSpecific(key: testQueueKey, value: ())
// ... later on, to test:
XCTAssertNotNil(DispatchQueue.getSpecific(key: testQueueKey), "callback should be called on specified queue")
Note that there's no value associated with the key (its type is Void), I'm only interested in the existence of the specific, not in it's value.
Important!
Make sure to keep a reference to the key, or cleanup after you're done using it. Otherwise a newly created key could use the same memory address, leading to weird behaviour. See: http://tom.lokhorst.eu/2018/02/leaky-abstractions-in-swift-with-dispatchqueue
Tests based on KFDoom's answer:
import XCTest
import Dispatch
class TestQueue: XCTestCase {
func testWithSpecificKey() {
let queue = DispatchQueue(label: "label")
let key = DispatchSpecificKey<Void>()
queue.setSpecific(key:key, value:())
let expectation1 = expectation(withDescription: "main")
let expectation2 = expectation(withDescription: "queue")
DispatchQueue.main.async {
if (DispatchQueue.getSpecific(key: key) == nil) {
expectation1.fulfill()
}
}
queue.async {
if (DispatchQueue.getSpecific(key: key) != nil) {
expectation2.fulfill()
}
}
waitForExpectations(withTimeout: 1, handler: nil)
}
func testWithPrecondition() {
let queue = DispatchQueue(label: "label")
let expectation1 = expectation(withDescription: "main")
let expectation2 = expectation(withDescription: "queue")
DispatchQueue.main.async {
dispatchPrecondition(condition: .notOnQueue(queue))
expectation1.fulfill()
}
queue.async {
dispatchPrecondition(condition: .onQueue(queue))
expectation2.fulfill()
}
waitForExpectations(withTimeout: 1, handler: nil)
}
}
One option is to set a precondition to test directly for the queue or set "specific" on it and retrieve it later. Further, one could use setSpecific and getSpecific. Alternatively, you can use a precondition check if you're on a queue so that should fulfill the "get current" need. src: https://github.com/duemunk/Async/blob/feature/Swift_3.0/AsyncTest/AsyncTests.swift
and
https://github.com/apple/swift/blob/master/stdlib/public/SDK/Dispatch/Dispatch.swift
One related option is to set a Main Queue / UI Queue precondition:
dispatchPrecondition(condition: .onQueue(DispatchQueue.main))
/*
Dispatch queue and NSOperations in Swift 3 Xcode 8
*/
protocol Container {
associatedtype ItemType
var count: Int { get }
mutating func pop()
mutating func push(item: ItemType)
mutating func append(item: ItemType)
subscript(i: Int) -> ItemType { get }
}
//Generic Function
struct GenericStack<Element> : Container {
mutating internal func push(item: Element) {
items.append(item)
}
mutating internal func pop() {
items.removeLast()
}
var items = [ItemType]()
internal subscript(i: Int) -> Element {
return items[i]
}
mutating internal func append(item: Element) {
self.push(item: item)
}
internal var count: Int { return items.count }
typealias ItemType = Element
}
var myGenericStack = GenericStack<String>()
myGenericStack.append(item: "Narendra")
myGenericStack.append(item: "Bade")
myGenericStack.count
myGenericStack.pop()
myGenericStack.count
//Some NSOperation
class ExploreOperationAndThread {
func performOperation() {
//Create queue
let queue = OperationQueue()
let operation1 = BlockOperation {
var count = myGenericStack.count
while count > 0 {
myGenericStack.pop()
count -= 1
}
}
operation1.completionBlock = {
print("Operation 1")
}
let operation2 = BlockOperation {
var count = 0
while count == 10 {
myGenericStack.append(item: "ItemAdded")
count += 1
}
}
operation2.completionBlock = {
print("Operation 2")
print(myGenericStack.items)
}
//Suppose operation 3 is related to UI
let operation3 = BlockOperation {
//run on main thread
DispatchQueue.main.async {
print(myGenericStack.items.count)
}
}
operation3.completionBlock = {
print("Operation 3")
print(myGenericStack.items.count)
}
//add operation into queue
queue.addOperation(operation3)
queue.addOperation(operation1)
queue.addOperation(operation2)
//Limit number of concurrent operation in queue
queue.maxConcurrentOperationCount = 1
//add dependancies
operation1.addDependency(operation2)
operation2.addDependency(operation3)
if myGenericStack.items.count == 0 {
//remove dependency
operation1.removeDependency(operation2)
}
}
}
//Other ways of using queues
DispatchQueue.global(qos: .userInitiated).async {
ExploreOperationAndThread().performOperation()
}
DispatchQueue.main.async {
print("I am performing operation on main theread asynchronously")
}
OperationQueue.main.addOperation {
var count = 0
while count == 10 {
myGenericStack.append(item: "Narendra")
count += 1
}
}
DispatchQueue.main.asyncAfter(deadline: .now() + 1.5 , execute: {
ExploreOperationAndThread().performOperation()
})
let queue2 = DispatchQueue(label: "queue2") //Default is serial queue
queue2.async {
print("asynchronously")
}

Block not really executing?

I'm trying to use a subclass of NSThread to run some commands. Before you recommend NSOperation or GCD, YES I need to use threads.
Below is my code and my output. The block is being created and added to the array and supposedly is being dequeued and run by the thread, but I don't see any output resulting from the running of my block. Why not?
import UIKit
class ViewController: UIViewController {
private let _queue = dispatch_queue_create("com.AaronLBratcher.ALBQueue", nil)
private let _thread = TestThread()
private let _lock = NSCondition()
override func viewDidLoad() {
super.viewDidLoad()
_thread.start()
var openSuccessful = false
dispatch_sync(_queue) {[unowned self] () -> Void in
self._lock.lock()
self._thread.openFile("file path here", completion: { (successful) -> Void in
print("completion block running...")
openSuccessful = successful
self._lock.signal()
self._lock.unlock()
})
self._lock.wait()
}
print("open operation complete")
print(openSuccessful)
}
final class TestThread:NSThread {
var _iterations = 0
var _lock = NSCondition()
var _blocks = [Any]()
func openFile(FilePath:String, completion:(successful:Bool) -> Void) {
print("queueing openFile...")
let block = {[unowned self] in
self._iterations = self._iterations + 1
print("opening file...")
completion(successful: true)
}
addBlock(block)
}
func addBlock(block:Any) {
_lock.lock()
_blocks.append(block)
_lock.signal()
_lock.unlock()
}
override func main() {
_lock.lock()
while true {
while _blocks.count == 0 {
print("waiting...")
_lock.wait()
}
print("extracting block...")
if let block = _blocks.first {
_blocks.removeFirst()
_lock.unlock()
print("running block...")
block;
}
_lock.lock()
}
}
}
}
Output:
queueing openFile...
waiting...
extracting block...
running block...
waiting...
The block isn't running because you just have block. You need block(), e.g.:
if let block = _blocks.first as? ()->() {
_blocks.removeFirst()
_lock.unlock()
print("running block...")
block()
}