Skip to content

Instantly share code, notes, and snippets.

@advantis
Created April 15, 2012 19:06
Show Gist options
  • Save advantis/2394358 to your computer and use it in GitHub Desktop.
Save advantis/2394358 to your computer and use it in GitHub Desktop.
iOS network activity indicator manager
//
// Copyright © 2011 Yuri Kotov
//
#import <Foundation/Foundation.h>
@interface ADVNetworkActivityIndicator : NSObject
+ (ADVNetworkActivityIndicator *) sharedIndicator;
- (void) start;
- (void) stop;
@end
//
// Copyright © 2011 Yuri Kotov
//
#import "ADVNetworkActivityIndicator.h"
static inline void CreateDispatchSourceAndSetHandler(dispatch_source_t *source, dispatch_block_t handler)
{
*source = dispatch_source_create(DISPATCH_SOURCE_TYPE_DATA_ADD, 0, 0, dispatch_get_main_queue());
dispatch_source_set_event_handler(*source, handler);
dispatch_resume(*source);
}
@implementation ADVNetworkActivityIndicator
{
signed long _count;
dispatch_source_t _increment;
dispatch_source_t _decrement;
}
#pragma mark - ADVNetworkActivityIndicator
+ (ADVNetworkActivityIndicator *) sharedIndicator
{
static dispatch_once_t predicate;
static ADVNetworkActivityIndicator *instance;
dispatch_once(&predicate, ^{ instance = [self new]; });
return instance;
}
- (void) start
{
dispatch_source_merge_data(_increment, 1ul);
}
- (void) stop
{
dispatch_source_merge_data(_decrement, 1ul);
}
#pragma mark - NSObject
- (id) init
{
self = [super init];
if (self)
{
__block __unsafe_unretained ADVNetworkActivityIndicator *this = self;
CreateDispatchSourceAndSetHandler(&_increment, ^{
if (0 == this->_count)
{
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
}
this->_count += dispatch_source_get_data(this->_increment);
});
CreateDispatchSourceAndSetHandler(&_decrement, ^{
this->_count -= dispatch_source_get_data(this->_decrement);
NSCAssert(-1 < this->_count, @"Unbalanced call to -[%@ stop]", [this class]);
if (0 == this->_count)
{
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
}
});
}
return self;
}
- (void) dealloc
{
dispatch_release(_decrement);
dispatch_release(_increment);
#if !__has_feature(objc_arc)
[super dealloc];
#endif
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment