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?

10 Answers
10

Leave a Comment