在Swift中如何在GCD主线程上调用带参数的方法? [英] In Swift how to call method with parameters on GCD main thread?

查看:25
本文介绍了在Swift中如何在GCD主线程上调用带参数的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我有一个函数可以创建 NSRURLSession 并使用

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 添加到调用视图控制器.我有一个函数叫做

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-adding 计算.如果我尝试在完成块内运行添加视图的代码,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?

推荐答案

现代版本的 Swift 使用 DispatchQueue.main.async 调度到主线程:

Modern versions of Swift use DispatchQueue.main.async to dispatch to the main thread:

DispatchQueue.main.async { 
  // your code here
}

在主队列之后调度,请使用:

DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  // your code here
}

使用旧版本的 Swift:

Older versions of Swift used:

dispatch_async(dispatch_get_main_queue(), {
  let delegateObj = UIApplication.sharedApplication().delegate as YourAppDelegateClass
  delegateObj.addUIImage("yourstring")
})

这篇关于在Swift中如何在GCD主线程上调用带参数的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆