如何使用线程在迅速?

dispatchOnMainThread:^{

    NSLog(@"Block Executed On %s", dispatch_queue_get_label(dispatch_get_current_queue()));

}];

当前回答

你必须将你想要在后台运行的更改与你想要在UI上运行的更新分开:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
    // do your task

    dispatch_async(dispatch_get_main_queue()) {
        // update some UI
    }
}

其他回答

好的答案,无论如何,我想分享我的面向对象的解决方案,直到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

dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0), {
    // Conversion into base64 string
    self.uploadImageString =  uploadPhotoDataJPEG.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.EncodingEndLineWithCarriageReturn)
})

Swift 3版本

Swift 3利用新的DispatchQueue类来管理队列和线程。要在后台线程上运行一些东西,你可以使用:

let backgroundQueue = DispatchQueue(label: "com.app.queue", qos: .background)
backgroundQueue.async {
    print("Run on background thread")
}

或者如果你想在两行代码中实现:

DispatchQueue.global(qos: .background).async {
    print("Run on background thread")

    DispatchQueue.main.async {
        print("We finished that.")
        // only back on the main thread, may you access UI:
        label.text = "Done."
    }
}

你也可以在本教程中获得一些关于Swift 3中GDC的深入信息。

来自Jameson Quave的教程

斯威夫特2

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
    //All stuff here
})

多用途螺纹功能

public enum QueueType {
        case Main
        case Background
        case LowPriority
        case HighPriority

        var queue: DispatchQueue {
            switch self {
            case .Main:
                return DispatchQueue.main
            case .Background:
                return DispatchQueue(label: "com.app.queue",
                                     qos: .background,
                                     target: nil)
            case .LowPriority:
                return DispatchQueue.global(qos: .userInitiated)
            case .HighPriority:
                return DispatchQueue.global(qos: .userInitiated)
            }
        }
    }

    func performOn(_ queueType: QueueType, closure: @escaping () -> Void) {
        queueType.queue.async(execute: closure)
    }

像这样使用它:

performOn(.Background) {
    //Code
}