最佳实践是定义可多次使用的可重用功能。
可重复使用的功能:
例如像AppDelegate.swift这样的全局函数。
func backgroundThread(_ delay: Double = 0.0, background: (() -> Void)? = nil, completion: (() -> Void)? = nil) {
dispatch_async(dispatch_get_global_queue(Int(QOS_CLASS_USER_INITIATED.value), 0)) {
background?()
let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)))
dispatch_after(popTime, dispatch_get_main_queue()) {
completion?()
}
}
}
注:雨燕2.0,更换QOS_CLASS_USER_INITIATED.value以上QOS_CLASS_USER_INITIATED.rawValue代替
用法:
A.要在后台运行一个进程并延迟3秒:
backgroundThread(3.0, background: {
// Your background function here
})
B.要在后台运行进程,然后在前台运行补全:
backgroundThread(background: {
// Your function here to run in the background
},
completion: {
// A function to run in the foreground when the background thread is complete
})
C.延迟3秒-注意在没有背景参数的情况下使用完成参数:
backgroundThread(3.0, completion: {
// Your delayed function here to be run in the foreground
})