如何使用线程在迅速?
dispatchOnMainThread:^{
NSLog(@"Block Executed On %s", dispatch_queue_get_label(dispatch_get_current_queue()));
}];
如何使用线程在迅速?
dispatchOnMainThread:^{
NSLog(@"Block Executed On %s", dispatch_queue_get_label(dispatch_get_current_queue()));
}];
当前回答
Swift 3.0 +
在Swift 3.0中,很多东西都被现代化了。在后台队列上运行一些东西看起来像这样:
DispatchQueue.global(qos: .userInitiated).async {
print("This is run on a background queue")
DispatchQueue.main.async {
print("This is run on the main queue, after the previous code in outer block")
}
}
Swift 1.2到2.3
let qualityOfServiceClass = QOS_CLASS_USER_INITIATED
let backgroundQueue = dispatch_get_global_queue(qualityOfServiceClass, 0)
dispatch_async(backgroundQueue, {
print("This is run on a background queue")
dispatch_async(dispatch_get_main_queue(), { () -> Void in
print("This is run on the main queue, after the previous code in outer block")
})
})
Pre Swift 1.2 -已知问题
从Swift 1.1开始,苹果在没有做一些修改的情况下不支持上述语法。传递qos_class_user_initialized实际上不起作用,而是使用Int(qos_class_user_initialized .value)。
有关更多信息,请参阅apple文档
其他回答
下面的代码是否有缺点(当需要启动前台屏幕之后)?
import Foundation
import UIKit
class TestTimeDelay {
static var connected:Bool = false
static var counter:Int = 0
static func showAfterDelayControl(uiViewController:UIViewController) {
NSLog("TestTimeDelay", "showAfterDelayControl")
}
static func tryReconnect() -> Bool {
counter += 1
NSLog("TestTimeDelay", "Counter:\(counter)")
return counter > 4
}
static func waitOnConnectWithDelay(milliseconds:Int, uiViewController: UIViewController) {
DispatchQueue.global(qos: .background).async {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + DispatchTimeInterval.milliseconds(milliseconds), execute: {
waitOnConnect(uiViewController: uiViewController)
})
}
}
static func waitOnConnect(uiViewController:UIViewController) {
connected = tryReconnect()
if connected {
showAfterDelayControl(uiViewController: uiViewController)
}
else {
waitOnConnectWithDelay(milliseconds: 200, uiViewController:uiViewController)
}
}
}
我真的很喜欢Dan Beaulieu的答案,但是它在Swift 2.2中不起作用,我认为我们可以避免那些讨厌的强制打开!
func backgroundThread(delay: Double = 0.0, background: (() -> Void)? = nil, completion: (() -> Void)? = nil) {
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0)) {
background?()
if let completion = completion{
let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)))
dispatch_after(popTime, dispatch_get_main_queue()) {
completion()
}
}
}
}
好的答案,无论如何,我想分享我的面向对象的解决方案,直到swift 5。
请查看它:AsyncTask
从概念上受到android的AsyncTask的启发,我用Swift写了自己的类
AsyncTask允许正确和简单地使用UI线程。该类允许执行后台操作并在UI线程上发布结果。
下面是一些用法示例
例1 -
AsyncTask(backgroundTask: {(p:String)->Void in//set BGParam to String and BGResult to Void
print(p);//print the value in background thread
}).execute("Hello async");//execute with value 'Hello async'
例2 -
let task2=AsyncTask(beforeTask: {
print("pre execution");//print 'pre execution' before backgroundTask
},backgroundTask:{(p:Int)->String in//set BGParam to Int & BGResult to String
if p>0{//check if execution value is bigger than zero
return "positive"//pass String "poitive" to afterTask
}
return "negative";//otherwise pass String "negative"
}, afterTask: {(p:String) in
print(p);//print background task result
});
task2.execute(1);//execute with value 1
它有两个泛型类型:
BGParam -执行时发送给任务的参数类型。 BGResult -后台计算结果的类型。 当你创建一个AsyncTask时,你可以将这些类型传递给任何你需要传入和传入后台任务的类型,但如果你不需要这些类型,你可以将其标记为未使用的,只需将其设置为:Void或使用更短的语法:()
当一个异步任务执行时,它经过3个步骤:
beforeTask:()->在任务执行之前在UI线程上调用的Void。 backgroundTask: (param:BGParam)->BGResult在后台线程立即调用 afterTask:(参数:BGResult)->在UI线程上调用后台任务结果的Void
在我们的iOS应用中,中央调度是用来处理多任务的。
您可以使用此代码
// Using time interval
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+1) {
print("Hello World")
}
// Background thread
queue.sync {
for i in 0..<10 {
print("Hello", i)
}
}
// Main thread
for i in 20..<30 {
print("Hello", i)
}
更多信息请访问这个链接:https://www.programminghub.us/2018/07/integrate-dispatcher-in-swift.html
dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0), {
// Conversion into base64 string
self.uploadImageString = uploadPhotoDataJPEG.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.EncodingEndLineWithCarriageReturn)
})