在我的应用程序中,我有一个函数,使一个nsururlsession和发送一个NSURLRequest使用

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

在这个任务的完成块中,我需要做一些计算,将一个UIImage添加到调用视图控制器中。我有一个func叫

func displayQRCode(receiveAddr, withAmountInBTC:amountBTC)

它做uiimage添加计算。如果我试图在完成块中运行视图添加代码,Xcode抛出一个错误,说我不能在后台进程中使用布局引擎。所以我在So上找到了一些代码,试图在主线程上排队一个方法:

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”添加到这个函数调用。我将如何做到这一点,或者有人可以建议一种向应用程序的主队列添加方法调用的最佳方法吗?


当前回答

//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()
})

其他回答

下面是更好的(IMO) Swifty/Cocoa风格语法,可以实现与其他答案相同的结果:

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

或者你可以使用流行的Async Swift库,代码更少,功能更丰富:

Async.main {
    // Your code here
}

Swift 3+ & Swift 4版本:

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

Swift 3和Xcode 9.2:

dispatch_async_on_main_queue {
    print("Hello")
}

斯威夫特2

使用尾随闭包就变成了:

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

尾随闭包是Swift的语法糖,允许在函数参数范围之外定义闭包。有关更多信息,请参阅Swift 2.2编程语言指南中的尾随闭包。

在dispatch_async情况下,API是func dispatch_async(queue: dispatch_queue_t, _block: dispatch_block_t),因为dispatch_block_t是()的类型别名-> Void -一个接收0个参数且没有返回值的闭包,block是函数的最后一个参数,我们可以在dispatch_async的外部作用域定义闭包。

//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()
})

如果你在闭包中使用self,不要忘记弱化self。

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