在Swift中,如何在GCD主线程上调用带有参数的方法? [英] In Swift how to call method with parameters on GCD main thread?
问题描述
在我的应用中,我有一个函数,该函数可以创建NSRURLSession并使用发送一个NSURLRequest
In my app I have a function that makes an NSRURLSession and sends out an NSURLRequest using
sesh.dataTaskWithRequest(req, completionHandler: {(data, response, error)
在此任务的完成块中,我需要进行一些计算,以将UIImage添加到调用的viewcontroller中.我有一个叫做
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)
执行添加UIImage的计算.如果我尝试在完成块内运行添加视图的代码,则Xcode会引发错误,提示我在后台进程中无法使用布局引擎.因此,我在SO上找到了一些代码,试图在主线程上将方法排队:
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)
})
但是,我不知道如何在此函数调用中添加参数"receiveAddr"和"amountBTC".我该怎么做,或者有人可以建议将方法调用添加到应用程序主队列的最佳方法?
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?
推荐答案
只需将其写在completion handler
中.无需使用dispatch_after
Just write this in completion handler
.No need to use dispatch_after
dispatch_async(dispatch_get_main_queue(), {
let delegateObj = UIApplication.sharedApplication().delegate as YourAppDelegateClass
delegateObj.addUIImage("yourstring")
})
快速3/4:
DispatchQueue.main.async {
let delegateObj = UIApplication.sharedApplication().delegate as YourAppDelegateClass
delegateObj.addUIImage("yourstring")
}
还用于在主队列上发送后
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
// your code here
}
用您的委托类替换YourAppDelegateClass
这篇关于在Swift中,如何在GCD主线程上调用带有参数的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!