Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
UIApplication+NetworkActivity keeps track of how many network operations you currently have and manages the NetworkActivityIndicator for you.
//
// UIApplication+NetworkActivity.h
//
// Created by Maciej Swic on 2013-04-29.
// Released under the MIT license.
//
#import <UIKit/UIKit.h>
@interface UIApplication (NetworkActivity)
+ (void)startNetworkActivity;
+ (void)finishNetworkActivity;
- (void)updateNetworkActivityIndicator;
@end
//
// UIApplication+NetworkActivity.m
//
// Created by Maciej Swic on 2013-04-29.
// Released under the MIT license.
//
#import "UIApplication+NetworkActivity.h"
@implementation UIApplication (NetworkActivity)
static NSLock *networkOperationCountLock;
static NSInteger networkOperationCount;
+ (void)startNetworkActivity {
[self createLock];
[networkOperationCountLock lock];
networkOperationCount++;
[networkOperationCountLock unlock];
[[UIApplication sharedApplication] updateNetworkActivityIndicator];
}
+ (void)finishNetworkActivity {
[self createLock];
[networkOperationCountLock lock];
networkOperationCount--;
[networkOperationCountLock unlock];
[[UIApplication sharedApplication] updateNetworkActivityIndicator];
}
+ (void)createLock {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
networkOperationCountLock = [NSLock new];
});
}
- (void)updateNetworkActivityIndicator {
[self setNetworkActivityIndicatorVisible:(networkOperationCount > 0 ? TRUE : FALSE)];
[networkOperationCountLock lock];
if (networkOperationCount < 0) {
networkOperationCount = 0;
}
[networkOperationCountLock unlock];
}
@end

Abizern commented Apr 25, 2014

This doesn't look like it's very thread safe.

Owner

maciekish commented Jul 28, 2014

@Abizern added a lock. Should be sufficient?

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