-
Notifications
You must be signed in to change notification settings - Fork 1
/
STConnectionManager.m
93 lines (76 loc) · 2.4 KB
/
STConnectionManager.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#import "STConnectionManager.h"
static STConnectionManager* sharedSTConnectionManager = nil;
@interface STConnectionManager ()
@property (nonatomic, assign, readwrite) NSUInteger runningConnectionsCount;
- (void)incrementConnectionCount;
- (void)decrementConnectionCount;
@end
@implementation STConnectionManager
#pragma mark -
#pragma mark Singleton Pattern
#pragma mark -
+ (STConnectionManager*)sharedSTConnectionManager {
@synchronized(self) {
if (sharedSTConnectionManager == nil) {
sharedSTConnectionManager = [[self alloc] init];
}
}
return sharedSTConnectionManager;
}
- (id)init {
if (self = [super init]) {
self.runningConnectionsCount = 0;
}
return self;
}
+ (id)allocWithZone:(NSZone*)zone {
@synchronized(self) {
if (sharedSTConnectionManager == nil) {
// assignment and return on first allocation
sharedSTConnectionManager = [super allocWithZone:zone];
return sharedSTConnectionManager;
}
}
return nil;
}
- (id)copyWithZone:(NSZone *)zone {
return self;
}
- (void)incrementConnectionCount {
BOOL movingToInUse;
movingToInUse = (self.runningConnectionsCount == 0);
if (movingToInUse) {
[self willChangeValueForKey:@"networkInUse"];
}
self.runningConnectionsCount += 1;
if (movingToInUse) {
[self didChangeValueForKey:@"networkInUse"];
}
}
- (void)decrementConnectionCount {
BOOL movingToNotInUse;
movingToNotInUse = (self.runningConnectionsCount == 1);
if (movingToNotInUse) {
[self willChangeValueForKey:@"networkInUse"];
}
self.runningConnectionsCount -= 1;
if (movingToNotInUse) {
[self didChangeValueForKey:@"networkInUse"];
}
}
- (void)startConnection:(STHTTPConnection*)connection withHandler:(STConnectionHandler)handler {
connection.completionHandler = ^(STHTTPConnection *connection) {
@synchronized (self) {
[self performSelectorOnMainThread:@selector(decrementConnectionCount) withObject:nil waitUntilDone:NO];
if (!connection.isCancelled) handler(connection);
}
};
@synchronized (self) {
[self performSelectorOnMainThread:@selector(incrementConnectionCount) withObject:nil waitUntilDone:NO];
[connection start];
}
}
- (void)setNetworkInUse:(BOOL)networkInUse {
@synchronized (self) { _networkInUse = networkInUse; }
}
@end