-
Notifications
You must be signed in to change notification settings - Fork 0
/
HttpOperation.m
342 lines (249 loc) · 10.5 KB
/
HttpOperation.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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
//
// HttpOperation.m
//
// Licensed by ruralcoder.com under the
// Creative Commons Attribution-ShareAlike 3.0 Unported License
#import "HttpOperation.h"
#import "NSErrorExtension.h"
#import "NSDictionaryExtension.h"
#import "HttpOperationDelegate.h"
@interface HttpOperation()
@property (nonatomic, retain) NSURLConnection *connection;
@property (nonatomic, retain) NSMutableData *data;
@end
@implementation HttpOperation
@synthesize connection;
@synthesize data;
@synthesize type = _type;
@synthesize delegate = _delegate;
@synthesize cookie = _cookie;
@synthesize resourceUrl = _resourceUrl;
@synthesize request = _request;
@synthesize executing = _executing;
@synthesize finished = _finished;
- (NSData*) responseData
{
return self.data;
}
- (id) initWithRequest:(NSURLRequest*)httpRequest type:(HttpOperations)httpType cookie:(id)object target:(id<HttpOperationDelegate>)target
{
NSParameterAssert(httpRequest != nil);
NSParameterAssert(target != nil);
self = [super init];
if (self)
{
self.executing = NO;
self.finished = NO;
_type = httpType;
_request = [httpRequest retain];
_delegate = [target retain];
_cookie = [object retain];
}
return self;
}
+ (void) startHttpGetOperationWithClient:(id<HttpOperationDelegate>)client
resource:(NSString*)resource
withPayload:(NSDictionary*)args
{
NetLog(@"HttpPostOperation - startOperationWithClient");
NSMutableDictionary *updatedArgs = [NSMutableDictionary dictionaryWithDictionary:args];
id cookie = [args objectForKey:ObjectKeyCookie];
[updatedArgs removeObjectForKey:ObjectKeyCookie];
[updatedArgs removeObjectForKey:ObjectKeyObjectId];
NSString *payload = [updatedArgs stringWithDelimeter:@"&" andKeyValueSeperator:@"=" urlEncode:YES];
NSString *link = [NSString stringWithFormat:@"%@?%@", resource, payload];
NSURL *resourceUrl = [NSURL URLWithString:link];
HttpLog(@"HTTP GET: %@", [resourceUrl absoluteString]);
NSMutableURLRequest *httpRequest = [[NSMutableURLRequest alloc] initWithURL:resourceUrl];
[httpRequest setTimeoutInterval:[ServiceSettings instance].connectionTimeout];
HttpOperation *operation = [[HttpOperation alloc] initWithRequest:httpRequest
type:HttpOperationGet
cookie:cookie
target:(id<HttpOperationDelegate>)client];
[httpRequest release];
[ApplicationController addOperationToQueue:operation];
[operation release];
}
+ (void) startHttpPostOperationWithClient:(id)client
resource:(NSString*)resource
withPayload:(NSDictionary*)args
{
NetLog(@"HttpPostOperation - startOperationWithClient");
NSMutableDictionary *updatedArgs = [NSMutableDictionary dictionaryWithDictionary:args];
id cookie = [args objectForKey:ObjectKeyCookie];
[updatedArgs removeObjectForKey:ObjectKeyCookie];
[updatedArgs removeObjectForKey:ObjectKeyObjectId];
NSURL *resourceUrl = [NSURL URLWithString:resource];
NSString *payload = [updatedArgs stringWithDelimeter:@"&" andKeyValueSeperator:@"="];
HttpLog(@"HTTP POST: %@", [resourceUrl absoluteString]);
NSMutableURLRequest *httpRequest = [[[NSMutableURLRequest alloc] initWithURL:resourceUrl] autorelease];
[httpRequest setTimeoutInterval:[ServiceSettings instance].connectionTimeout];
[httpRequest setHTTPMethod:@"POST"];
[httpRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-type"];
[httpRequest setValue:[NSString stringWithFormat:@"%d", [payload length]] forHTTPHeaderField:@"Content-length"];
[httpRequest setHTTPBody:[payload dataUsingEncoding:NSUTF8StringEncoding]];
HttpOperation *operation = [[HttpOperation alloc] initWithRequest:httpRequest
type:HttpOperationPost
cookie:cookie
target:(id<HttpOperationDelegate>)client];
[ApplicationController addOperationToQueue:operation];
[operation release];
}
- (void) dealloc
{
AllocLog(@"HttpOperation - dealloc");
self.connection = nil;
self.data = nil;
[_cookie release];
[_delegate release];
[_request release];
[super dealloc];
}
- (void) start
{
NetLog(@"HttpOperation - start");
if ([self isCancelled])
{
// Must move the operation to the finished state if it is canceled.
[self willChangeValueForKey:@"isFinished"];
self.finished = YES;
[self didChangeValueForKey:@"isFinished"];
return;
}
// If the operation is not canceled, begin executing the task.
[self willChangeValueForKey:@"isExecuting"];
[NSThread detachNewThreadSelector:@selector(main) toTarget:self withObject:nil];
self.executing = YES;
[self didChangeValueForKey:@"isExecuting"];
}
- (void)completeOperation {
NetLog(@"HttpOperation - completeOperation");
self.connection = nil;
[self willChangeValueForKey:@"isFinished"];
[self willChangeValueForKey:@"isExecuting"];
self.executing = NO;
self.finished = YES;
[self didChangeValueForKey:@"isExecuting"];
[self didChangeValueForKey:@"isFinished"];
}
- (void) main
{
NetLog(@"HttpOperation - main");
@autoreleasepool {
@try
{
[self willChangeValueForKey:@"isExecuting"];
self.executing = YES;
[self didChangeValueForKey:@"isExecuting"];
self.connection = [[NSURLConnection alloc] initWithRequest:self.request delegate:self];
if (self.connection == nil)
[self completeOperation];
else
{
[self.connection scheduleInRunLoop:[NSRunLoop currentRunLoop]
forMode:NSDefaultRunLoopMode];
[self.connection start];
while (![self isFinished]) {
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}
}
}
@catch (NSException *exception)
{
[self.delegate performSelectorOnMainThread:@selector(operationException:)
withObject:exception
waitUntilDone:YES];
}
}
}
- (void) cancel
{
[self.connection cancel];
}
- (BOOL)isConcurrent
{
return YES;
}
- (BOOL)isExecuting {
return self.executing;
}
- (BOOL)isFinished {
return self.finished;
}
#pragma mark NSURLConnection delegate methods
// Handle errors in the download by showing an alert to the user. This is a very
// simple way of handling the error, partly because this application does not have any offline
// functionality for the user. Most real applications should handle the error in a less obtrusive
// way and provide offline functionality to the user.
//
- (void)handleError:(NSError *)error
{
NetLog(@"HttpPostOperation - handleError: '%@'", [error description]);
[self.delegate performSelectorOnMainThread:@selector(operationError:)
withObject:error
waitUntilDone:YES];
[self completeOperation];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NetLog(@"HttpPostOperation - connectionDidFinishLoading");
[self.delegate performSelectorOnMainThread:@selector(operationCompleted:)
withObject:self
waitUntilDone:YES];
[self completeOperation];
}
// The following are delegate methods for NSURLConnection. Similar to callback functions, this is
// how the connection object, which is working in the background, can asynchronously communicate back
// to its delegate on the thread from which it was started - in this case, the main thread.
//
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NetLog(@"HttpPostOperation - didReceiveResponse");
// check for HTTP status code for proxy authentication failures
// anything in the 200 to 299 range is considered successful,
// also make sure the MIMEType is correct:
//
if ([response respondsToSelector:@selector(statusCode)] == NO)
{
NetLog(@"WARNING: Not an HTTP response");
NetLog(@"%@", [response description]);
return;
}
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
NetLog(@"POST response code: %d", [httpResponse statusCode]);
if (([httpResponse statusCode]/100) != 2) // HTTP 200 == OK
{
NSError *error = [NSError errorWithDomain:@"HTTP"
code:[httpResponse statusCode]
title:@"HTTP Error"
description:@"Error message displayed when receving a connection error."];
[self handleError:error];
[self completeOperation];
}
if ([[response MIMEType] isEqual:@"application/json"] == NO)
NetLog(@"WARNING: Server did not return JSON got '%@' instead.", [response MIMEType]);
self.data = [NSMutableData data];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)dataPacket
{
NetLog(@"HttpPostOperation - didReceiveData");
[self.data appendData:dataPacket];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NetLog(@"HttpPostOperation - didFailWithError");
if ([error code] == kCFURLErrorNotConnectedToInternet)
{
NSError *noConnectionError = [NSError errorWithDomain:NSCocoaErrorDomain
code:kCFURLErrorNotConnectedToInternet
title:@"No Connection Error"
description:@"Error message displayed when not connected to the Internet."];
[self handleError:noConnectionError];
}
else
{
// otherwise handle the error generically
[self handleError:error];
}
[self completeOperation];
}
@end