Skip to content

Instantly share code, notes, and snippets.

@maciekish
Last active November 27, 2021 06:58
Show Gist options
  • Save maciekish/6052297 to your computer and use it in GitHub Desktop.
Save maciekish/6052297 to your computer and use it in GitHub Desktop.
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
Copy link

Abizern commented Apr 25, 2014

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

@maciekish
Copy link
Author

@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