Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you show iOS network indicator while TPL Task is running?

I'm heavily using Task Parallel Library when talking to server API.
I would like to show iOS network indicator while any of these tasks is currently running.

How do I go about that?

like image 649
Dan Abramov Avatar asked Jan 28 '13 11:01

Dan Abramov


2 Answers

I created this class to wrap NetworkActivityIndicatorVisible into a pair of enter/leave methods.

public static class NetworkIndicator
{
    static int _counter;

    public static void EnterActivity ()
    {
        Interlocked.Increment (ref _counter);
        RefreshIndicator ();
    }

    public static void LeaveActivity ()
    {
        Interlocked.Decrement (ref _counter);
        RefreshIndicator ();
    }

    public static void AttachToTask (Task task)
    {
        if (task.IsCanceled || task.IsCanceled || task.IsFaulted)
            return;

        EnterActivity ();
        task.ContinueWith (t => {
            LeaveActivity ();
        });
    }

    static void RefreshIndicator ()
    {
        UIApplication.SharedApplication.NetworkActivityIndicatorVisible =
            (_counter > 0);
    }
}

Then I added two extension methods for convenience:

public static class TaskExtensions
{
    public static Task WithNetworkIndicator (this Task task)
    {
        NetworkIndicator.AttachToTask (task);
        return task;
    }

    public static Task<TResult> WithNetworkIndicator<TResult> (this Task<TResult> task)
    {
        NetworkIndicator.AttachToTask (task);
        return task;
    }
}

How I'm wrapping it:

var task = Api.QueryNotifications (AuthManager.CurrentProfile.Id, NotificationType.All, until, cached)
    .WithNetworkIndicator ();

Then I'm using the task as usual.

like image 169
Dan Abramov Avatar answered Oct 04 '22 18:10

Dan Abramov


Try This code in NetworkActivityIndicatorVisible:

[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
like image 42
San Avatar answered Oct 04 '22 18:10

San