J'ai écrit un singleton qui résout le problème des connexions multiples en gardant un compteur de ce qui se passe (pour éviter de supprimer l'état lorsqu'une connexion revient mais qu'une autre est toujours active) :
Le fichier d'en-tête :
#import <Foundation/Foundation.h>
@interface RMActivityIndicator : NSObject
-(void)increaseActivity;
-(void)decreaseActivity;
-(void)noActivity;
+(RMActivityIndicator *)sharedManager;
@end
et la mise en œuvre :
#import "RMActivityIndicator.h"
@interface RMActivityIndicator ()
@property(nonatomic,assign) unsigned int activityCounter;
@end
@implementation RMActivityIndicator
- (id)init
{
self = [super init];
if (self) {
self.activityCounter = 0;
}
return self;
}
-(void)increaseActivity{
@synchronized(self) {
self.activityCounter++;
}
[self updateActivity];
}
-(void)decreaseActivity{
@synchronized(self) {
if (self.activityCounter>0) self.activityCounter--;
}
[self updateActivity];
}
-(void)noActivity{
self.activityCounter = 0;
[self updateActivity];
}
-(void)updateActivity{
UIApplication* app = [UIApplication sharedApplication];
app.networkActivityIndicatorVisible = (self.activityCounter>0);
}
#pragma mark -
#pragma mark Singleton instance
+(RMActivityIndicator *)sharedManager {
static dispatch_once_t pred;
static RMActivityIndicator *shared = nil;
dispatch_once(&pred, ^{
shared = [[RMActivityIndicator alloc] init];
});
return shared;
}
@end
Exemple :
[[RMActivityIndicator sharedManager]increaseActivity];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:self.networkReceiveProcessQueue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
[[RMActivityIndicator sharedManager]decreaseActivity];
}