Last active
June 8, 2017 13:10
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@autoaim800 Sorry, I'm without Mac at the moment :(