Skip to content

Instantly share code, notes, and snippets.

@douglasjunior
Last active June 8, 2017 13:10
Show Gist options
  • Save douglasjunior/ef80ba0b80059a04e16d to your computer and use it in GitHub Desktop.
Save douglasjunior/ef80ba0b80059a04e16d to your computer and use it in GitHub Desktop.
Basic AsyncTask implementation in Swift. Like http://developer.android.com/reference/android/os/AsyncTask.html
//
// AsyncTask.swift
//
// Created by Douglas Nassif Roma Junior on 08/06/15.
// Copyright (c) 2015 Douglas Nassif Roma Junior. All rights reserved.
//
import Foundation
class AsyncTask<Params, Progress, Result> : NSObject {
var backgroundTask : (params: Array<Params>?) -> Result? = {(params: Array<Params>?) -> Result? in return nil};
var beforeExecute : () -> Void = {};
var afterExecute : (result : Result?) -> Void = {(result : Result?) -> Void in };
private var interrupted = false;
func execute(params : Array<Params>){
dispatch_after(0, dispatch_get_main_queue(), {
if (self.beforeExecute != nil) {
self.beforeExecute();
}
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
var result = self.backgroundTask(params: params);
dispatch_after(0, dispatch_get_main_queue(), {
self.afterExecute(result: result);
})
})
})
}
func execute(){
self.execute(Array());
}
func interrupt(){
interrupted = true;
}
func isInterrupted() -> Bool {
return interrupted;
}
}
@autoaim800
Copy link

Hi Douglas, can you also provide a swift3 version for the above class. My xcode converted it into some error. Thanks.

@douglasjunior
Copy link
Author

@autoaim800 Sorry, I'm without Mac at the moment :(

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment