iOS/Objective-C equivalent of Android's AsyncTask

Viewed 32237

I'm familiar with using AsyncTask in Android: create a subclass, call execute on an instance of the subclass and onPostExecute is called on the UI thread or main thread. What's the equivalent in iOS?

5 Answers

Here is a c# Xamarin.iOS version with PusblishProgress:

internal abstract class AsyncTask : NSObject
{
    protected abstract nint DoInBackground(NSArray parameters);

    protected abstract void PostExecute(nint result);

    public void ExecuteParameters(NSArray @params)
    {
        this.PreExecute();

        DispatchQueue.GetGlobalQueue(DispatchQueuePriority.Default).DispatchAsync(() =>
        {
            //We're on a Background thread
            var result = this.DoInBackground(@params);
            DispatchQueue.MainQueue.DispatchAsync(() => {
                // We're on the main thread
                this.PostExecute(result);
            });
        });

    }

    protected abstract void PreExecute();

    protected void PublishProgress(NSArray parameters)
    {
        InvokeOnMainThread(() => {
            // We're on the main thread
            this.OnProgressUpdate(parameters);
        });
    }

    protected abstract void OnProgressUpdate(NSArray parameters);
}

And implementation:

internal class MyAsyncTask : AsyncTask
{
    protected override void OnProgressUpdate(NSArray parameters)
    {
        // This runs on the UI Thread
    }

    protected override nint DoInBackground(NSArray parameters)
    {
        // Do some background work
        // ....
        var progress = NSArray.FromObjects(1, "Done step 1");
        PublishProgress(progress);

        return 0;
     }

     protected override void PostExecute(nint result)
     {
         // This runs on the UI Thread

     }

     protected override void PreExecute()
     {
        // This runs on the UI Thread

     }
}
Related