[parameters] In Swift how to call method with parameters on GCD main thread?

In my app I have a function that makes an NSRURLSession and sends out an NSURLRequest using

sesh.dataTaskWithRequest(req, completionHandler: {(data, response, error)

In the completion block for this task, I need to do some computation that adds a UIImage to the calling viewcontroller. I have a func called

func displayQRCode(receiveAddr, withAmountInBTC:amountBTC)

that does the UIImage-adding computation. If I try to run the view-adding code inside of the completion block, Xcode throws an error saying that I can't use the layout engine while in a background process. So I found some code on SO that tries to queue a method on the main thread:

let time = dispatch_time(DISPATCH_TIME_NOW, Int64(0.0 * Double(NSEC_PER_MSEC)))

dispatch_after(time, dispatch_get_main_queue(), {
    let returned = UIApplication.sharedApplication().sendAction("displayQRCode:", to: self.delegate, from: self, forEvent: nil)
})

However, I don't know how to add the parameters "receiveAddr" and "amountBTC" to this function call. How would I do this, or can someone suggest an optimal way for adding a method call to the application's main queue?

This question is related to parameters swift grand-central-dispatch

The answer is


Swift 3+ & Swift 4 version:

DispatchQueue.main.async {
    print("Hello")
}

Swift 3 and Xcode 9.2:

dispatch_async_on_main_queue {
    print("Hello")
}

Here's a nice little global function you can add for a nicer syntax:

func dispatch_on_main(block: dispatch_block_t) {
    dispatch_async(dispatch_get_main_queue(), block)
}

And usage

dispatch_on_main {
    // Do some UI stuff
}

Swift 2

Using Trailing Closures this becomes:

dispatch_async(dispatch_get_main_queue()) {
    self.tableView.reloadData()
}

Trailing Closures is Swift syntactic sugar that enables defining the closure outside of the function parameter scope. For more information see Trailing Closures in Swift 2.2 Programming Language Guide.

In dispatch_async case the API is func dispatch_async(queue: dispatch_queue_t, _ block: dispatch_block_t) since dispatch_block_t is type alias for () -> Void - A closure that receives 0 parameters and does not have a return value, and block being the last parameter of the function we can define the closure in the outer scope of dispatch_async.


Don't forget to weakify self if you are using self inside of the closure.

dispatch_async(dispatch_get_main_queue(),{ [weak self] () -> () in
    if let strongSelf = self {
        self?.doSomething()
    }
})

The proper way to do this is to use dispatch_async in the main_queue, as I did in the following code

dispatch_async(dispatch_get_main_queue(), {
    (self.delegate as TBGQRCodeViewController).displayQRCode(receiveAddr, withAmountInBTC:amountBTC)
})

//Perform some task and update UI immediately.
DispatchQueue.global(qos: .userInitiated).async {  
    // Call your function here
    DispatchQueue.main.async {  
        // Update UI
        self.tableView.reloadData()  
    }
}

//To call or execute function after some time
DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) {
    //Here call your function
}

//If you want to do changes in UI use this
DispatchQueue.main.async(execute: {
    //Update UI
    self.tableView.reloadData()
})

Reload collectionView on Main Thread

DispatchQueue.main.async {
    self.collectionView.reloadData()
}

Here's the nicer (IMO) Swifty/Cocoa style syntax to achieve the same result as the other answers:

NSOperationQueue.mainQueue().addOperationWithBlock({
    // Your code here
})

Or you could grab the popular Async Swift library for even less code and more functionality:

Async.main {
    // Your code here
}

Examples related to parameters

Stored procedure with default parameters AngularJS ui router passing data between states without URL C#: HttpClient with POST parameters HTTP Request in Swift with POST method In Swift how to call method with parameters on GCD main thread? How to pass parameters to maven build using pom.xml? Default Values to Stored Procedure in Oracle How do you run a .exe with parameters using vba's shell()? How to set table name in dynamic SQL query? How to pass parameters or arguments into a gradle task

Examples related to swift

Make a VStack fill the width of the screen in SwiftUI Xcode 10.2.1 Command PhaseScriptExecution failed with a nonzero exit code Command CompileSwift failed with a nonzero exit code in Xcode 10 Convert Json string to Json object in Swift 4 iOS Swift - Get the Current Local Time and Date Timestamp Xcode 9 Swift Language Version (SWIFT_VERSION) How do I use Safe Area Layout programmatically? How can I use String substring in Swift 4? 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator Safe Area of Xcode 9 The use of Swift 3 @objc inference in Swift 4 mode is deprecated?

Examples related to grand-central-dispatch

Waiting until the task finishes How to create dispatch queue in Swift 3 How do I write dispatch_after GCD in Swift 3, 4, and 5? How do I dispatch_sync, dispatch_async, dispatch_after, etc in Swift 3, Swift 4, and beyond? In Swift how to call method with parameters on GCD main thread? EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) on dispatch_semaphore_dispose dispatch_after - GCD in Swift? Does dispatch_async(dispatch_get_main_queue(), ^{...}); wait until done? Waiting until two async blocks are executed before starting another block NSOperation vs Grand Central Dispatch