Reputation:
How can I create an asyncTask
in Swift? I want to call my loadPage()
function in the background (which will load the page from server), and I want to handle the response in postExecute(after background task)
Upvotes: 0
Views: 131
Reputation: 24040
You can use the Grand Central Dispatch to run threads.
class ThreadsFromSwiftEssentialsBook {
class func runOnBackgroundThread(fn:()->()) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),fn)
}
class func runOnUIThread(fn:()->()) {
if NSThread.isMainThread() {
fn()
} else {
dispatch_async(dispatch_get_main_queue(), fn)
}
}
}
(Implementation is MIT licensed here: https://github.com/alblue/com.packtpub.swift.essentials/blob/master/RepositoryBrowser/RepositoryBrowser/Threads.swift)
Upvotes: 1