-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathDataService.m
221 lines (199 loc) · 8.23 KB
/
DataService.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
#import "DataService.h"
#define DATA_SERVICE_DOMAIN @"DataService"
@interface DataService ()
@property (nonatomic, retain) NSMutableData *receivedData;
@property (nonatomic, retain) NSURLConnection *urlConnection;
@property (nonatomic, copy) void (^onReceiveBlock)(id, NSNumber*, NSDictionary*);
@property (nonatomic, copy) void (^onErrorBlock)(NSError*);
// Response properties: generate hidden setters
@property(nonatomic, retain, readwrite) NSDictionary *responseHeaders;
@property(nonatomic, readwrite) long long expectedContentLength;
@property(nonatomic, retain, readwrite) NSString *textEncodingName;
@property(nonatomic, retain, readwrite) NSString *MIMEType;
@property(nonatomic, retain, readwrite) NSString *suggestedFilename;
@end
@implementation DataService
@synthesize requestURL = _requestURL;
@synthesize statusCode = _statusCode;
@synthesize receivedData = _receivedData;
@synthesize urlConnection = _urlConnection;
@synthesize onReceiveBlock = _onReceiveBlock;
@synthesize onErrorBlock = _onErrorBlock;
@synthesize inProgress = _inProgress;
@synthesize responseHeaders = _responseHeaders;
@synthesize expectedContentLength = _expectedContentLength;
@synthesize textEncodingName = _textEncodingName;
@synthesize MIMEType = _MIMEType;
@synthesize suggestedFilename = _suggestedFilename;
#pragma mark - Initialization
+ (DataService*)service{
return [[[DataService alloc] init] autorelease];
}
#pragma mark - Request
-(void)requestWithURL:(NSURL*)url
method:(NSString*)method
headers:(NSDictionary*)headers
bodyStream:(NSInputStream*)bodyStream
cachePolicy:(NSURLRequestCachePolicy)cachePolicy
timeoutInterval:(NSTimeInterval)timeoutInterval
receiveHandler:(void (^)(id, NSNumber*, NSDictionary*))receiveHandler
errorHandler:(void (^)(NSError*))errorHandler {
[self retain];
self.onReceiveBlock = receiveHandler;
self.onErrorBlock = errorHandler;
self.requestURL = url;
self.responseHeaders = nil;
self.expectedContentLength = 0;
self.textEncodingName = nil;
self.MIMEType = nil;
self.suggestedFilename = nil;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:self.requestURL cachePolicy:cachePolicy timeoutInterval:timeoutInterval];
for (NSString *header in headers) {
[request addValue:[headers objectForKey:header] forHTTPHeaderField:header];
}
[request setHTTPShouldUsePipelining:YES];
[request setHTTPMethod:method];
[request setHTTPBodyStream:bodyStream];
[_urlConnection cancel];
[_urlConnection release];
_urlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
[_urlConnection scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
[_urlConnection start];
_inProgress = !!_urlConnection;
if (_urlConnection) {
self.receivedData = [NSMutableData data];
} else {
NSDictionary *errorInfo = [NSDictionary dictionaryWithObject:@"Failed to create connection" forKey:NSLocalizedDescriptionKey];
self.onErrorBlock([NSError errorWithDomain:DATA_SERVICE_DOMAIN code:0 userInfo:errorInfo]);
self.urlConnection = nil;
[self release];
}
}
-(void)requestWithURL:(NSURL *)url
method:(NSString *)method
headers:(NSDictionary *)headers
body:(NSData *)body
receiveHandler:(void (^)(id, NSNumber *, NSDictionary*))receiveHandler
errorHandler:(void (^)(NSError *))errorHandler {
NSMutableDictionary *newHeaders = [NSMutableDictionary dictionaryWithDictionary:headers];
if (body) {
[newHeaders setObject:[NSString stringWithFormat:@"%d", [body length]] forKey:@"Content-Length"];
}
[self requestWithURL:url
method:method
headers:newHeaders
bodyStream:body ? [NSInputStream inputStreamWithData:body] : nil
receiveHandler:receiveHandler
errorHandler:errorHandler];
}
-(void)requestWithURL:(NSURL*)url
method:(NSString*)method
headers:(NSDictionary*)headers
bodyStream:(NSInputStream*)bodyStream
receiveHandler:(void (^)(id, NSNumber*, NSDictionary*))receiveHandler
errorHandler:(void (^)(NSError*))errorHandler {
[self requestWithURL:url
method:method
headers:headers
bodyStream:bodyStream
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
timeoutInterval:60.0
receiveHandler:receiveHandler
errorHandler:errorHandler];
}
#pragma mark - Receive
- (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)response{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
self.statusCode = [httpResponse statusCode];
self.responseHeaders = [httpResponse allHeaderFields];
self.expectedContentLength = [httpResponse expectedContentLength];
self.textEncodingName = [httpResponse textEncodingName];
self.MIMEType = [httpResponse MIMEType];
self.suggestedFilename = [httpResponse suggestedFilename];
[self.receivedData setLength:0];
}
- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data{
[self.receivedData appendData:data];
}
- (void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error{
_inProgress = NO;
self.receivedData = nil;
self.onReceiveBlock = nil;
self.responseHeaders = nil;
self.expectedContentLength = 0;
self.textEncodingName = nil;
self.MIMEType = nil;
self.suggestedFilename = nil;
self.urlConnection = nil;
if (self.onErrorBlock) {
// Hold on to the block so that this DataService can be used for new requests in the callback.
void (^onErrorBlock)(NSError*) = [self.onErrorBlock retain];
self.onErrorBlock = nil;
onErrorBlock(error);
[onErrorBlock release];
}
[self release];
}
- (void)connectionDidFinishLoading:(NSURLConnection*)connection{
_inProgress = NO;
// check to see if the status code is an error code and react appropriately
if (self.statusCode / 100 == RESPONSE_CLIENT_ERROR / 100 || self.statusCode / 100 == RESPONSE_SERVER_ERROR / 100) {
NSString *errorString = [[[NSString alloc] initWithData:self.receivedData encoding:NSUTF8StringEncoding] autorelease];
NSDictionary *errorInfo = [NSDictionary dictionaryWithObject:errorString forKey:NSLocalizedDescriptionKey];
NSError *error = [NSError errorWithDomain:DATA_SERVICE_DOMAIN code:self.statusCode userInfo:errorInfo];
[self connection:connection didFailWithError:error];
return;
}
self.onErrorBlock = nil;
self.urlConnection = nil;
// Hold on to required values so that this DataService can be reused from the callback.
NSData *receivedData = [self.receivedData retain];
NSDictionary *responseHeaders = [self.responseHeaders retain];
self.receivedData = nil;
self.responseHeaders = nil;
self.expectedContentLength = 0;
self.textEncodingName = nil;
self.MIMEType = nil;
self.suggestedFilename = nil;
if (self.onReceiveBlock) {
void (^onReceiveBlock)(id, NSNumber*, NSDictionary*) = [self.onReceiveBlock retain];
self.onReceiveBlock = nil;
onReceiveBlock([NSData dataWithData:receivedData], [NSNumber numberWithInteger:self.statusCode], responseHeaders);
[onReceiveBlock release];
}
[receivedData release];
[responseHeaders release];
[self release];
}
#pragma mark - Cleanup
- (void)cancel{
[self.urlConnection cancel];
self.urlConnection = nil;
self.requestURL = nil;
self.receivedData = nil;
self.onReceiveBlock = nil;
self.onErrorBlock = nil;
self.responseHeaders = nil;
self.expectedContentLength = 0;
self.textEncodingName = nil;
self.MIMEType = nil;
self.suggestedFilename = nil;
if (_inProgress) {
[self release];
}
_inProgress = NO;
}
- (void)dealloc{
self.receivedData = nil;
self.requestURL = nil;
self.onReceiveBlock = nil;
self.onErrorBlock = nil;
self.urlConnection = nil;
self.responseHeaders = nil;
self.expectedContentLength = 0;
self.textEncodingName = nil;
self.MIMEType = nil;
self.suggestedFilename = nil;
[super dealloc];
}
@end