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?
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.
Try This code in NetworkActivityIndicatorVisible:
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With