/
MBURLConnectionOperation.m
295 lines (262 loc) · 9.21 KB
/
MBURLConnectionOperation.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
//
// MBURLConnectionOperation.m
// MBRequest
//
// Created by Sebastian Celis on 2/27/12.
// Copyright (c) 2012 Mobiata, LLC. All rights reserved.
//
#import "MBURLConnectionOperation.h"
#import "MBRequestError.h"
#import "MBRequestLocalization.h"
#import "MBRequestLog.h"
#import "MBURLConnectionOperationSubclass.h"
@interface MBURLConnectionOperation ()
@property (atomic, strong, readwrite) NSURLConnection *connection;
@property (atomic, strong, readwrite) NSMutableData *incrementalResponseData;
@property (atomic, strong, readwrite) NSURLResponse *response;
@property (atomic, strong, readwrite) NSData *responseData;
@property (atomic, strong, readwrite) NSError *error;
@property (atomic, assign) CFRunLoopRef runLoop;
@property (atomic, assign) BOOL runLoopIsRunning;
@property (atomic, assign) BOOL shouldCancel;
@end
@implementation MBURLConnectionOperation
#pragma mark - Accessors
- (void)setResponseDataOverride:(NSData *)data
{
[self setResponseData:data];
}
#pragma mark - Main Functionality
- (void)main
{
if ([self request] == nil)
{
[NSException raise:NSInternalInconsistencyException format:@"%@: Unable to send request. No NSURLRequest object set!", self];
}
if ([self shouldCancel])
{
[self cancelOperation];
[self finish];
}
else
{
#ifdef MB_DEBUG_REQUESTS
MBRequestLog(@"Sending %@ Request: %@", [[self request] HTTPMethod], [[self request] URL]);
MBRequestLog(@"Headers: %@", [[self request] allHTTPHeaderFields]);
NSString *bodyString = [[NSString alloc] initWithData:[[self request] HTTPBody] encoding:NSUTF8StringEncoding];
if ([bodyString length] > 0)
{
MBRequestLog(@"Body: %@", [[NSString alloc] initWithData:[[self request] HTTPBody] encoding:NSUTF8StringEncoding]);
}
#endif
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:[self request]
delegate:self
startImmediately:NO];
[self setConnection:connection];
if ([self connection] == nil)
{
NSLog(@"NSURLConnection's initWithRequest returned nil for %@. How is this possible?", [self request]);
NSString *message = MBRequestLocalizedString(@"unknown_error_occurred", @"An unknown error has occurred.");
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:message forKey:NSLocalizedDescriptionKey];
NSError *error = [NSError errorWithDomain:MBRequestErrorDomain
code:MBRequestErrorCodeUnknown
userInfo:userInfo];
[self setError:error];
[self finish];
}
else
{
[[self connection] start];
[self setRunLoop:CFRunLoopGetCurrent()];
[self setRunLoopIsRunning:YES];
CFRunLoopRun();
}
}
}
- (void)cancel
{
if (![self isCancelled] && ![self isFinished])
{
// Defer the actual cancellation to a later iteration of the operation runloop.
[self setShouldCancel:YES];
}
}
- (void)cancelFromRunLoop
{
[self setShouldCancel:NO];
[[self connection] cancel];
[self setConnection:nil];
dispatch_async(dispatch_get_main_queue(), ^{
// We run this on the main thread to ensure safe cleanup of the operation and
// the run loop. Without this block, it would be possible for [self cancelOperation]
// to remove the NSOperartion from the NSOperationQueue and thus immediately deallocate
// the operation before [self finish] can complete successfully.
[self cancelOperation];
[self finish];
});
}
- (void)cancelOperation
{
[super cancel];
}
- (void)finish
{
if (![self isCancelled] && ![self isFinished])
{
[[self delegate] connectionOperationDidFinish:self];
}
// Break the retain cycle. We no longer need to retain our delegate since we never need to
// reference it again. This must be done on the runloop (if it is running) since the runloop's
// thread may be *just* about to send a message to the delegate.
[self setDelegate:nil];
if ([self isExecuting] && [self runLoopIsRunning])
{
CFRunLoopStop([self runLoop]);
[self setRunLoop:NULL];
[self setRunLoopIsRunning:NO];
}
}
- (void)handleResponse
{
#ifdef MB_DEBUG_REQUESTS
if ([[self responseData] length] > 0)
{
NSString *responseString = [self responseDataAsUTF8String];
if ([responseString length] > 0)
{
MBRequestLog(@"Response String: %@", [self responseDataAsUTF8String]);
}
}
#endif
}
#pragma mark - Helper Methods
- (NSString *)responseDataAsUTF8String
{
return [[NSString alloc] initWithData:[self responseData] encoding:NSUTF8StringEncoding];
}
#pragma mark - NSURLConnectionDelegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
if (![self isCancelled] && ![self isFinished])
{
if ([self shouldCancel])
{
[self cancelFromRunLoop];
}
else
{
[self setResponse:response];
long long capacity = [response expectedContentLength];
capacity = (capacity == NSURLResponseUnknownLength) ? 1024 : capacity;
capacity = MIN(capacity, 1024 * 1000);
[self setIncrementalResponseData:[NSMutableData dataWithCapacity:(NSUInteger)capacity]];
}
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
if (![self isCancelled] && ![self isFinished])
{
if ([self shouldCancel])
{
[self cancelFromRunLoop];
}
else
{
[[self incrementalResponseData] appendData:data];
if ([_delegate respondsToSelector:@selector(connectionOperation:didReceiveBodyData:totalBytesRead:totalBytesExpectedToRead:)])
{
[_delegate connectionOperation:self
didReceiveBodyData:[data length]
totalBytesRead:[[self incrementalResponseData] length]
totalBytesExpectedToRead:[[self response] expectedContentLength]];
}
}
}
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
if (![self isCancelled] && ![self isFinished])
{
if ([self shouldCancel])
{
[self cancelFromRunLoop];
}
else
{
[self setError:error];
MBRequestLog(@"Request Error: %@", [self error]);
[self handleResponse];
[self finish];
}
}
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
if (![self isCancelled] && ![self isFinished])
{
if ([self shouldCancel])
{
[self cancelFromRunLoop];
}
else
{
[self setResponseData:[NSData dataWithData:[self incrementalResponseData]]];
[self setIncrementalResponseData:nil];
[self handleResponse];
[self finish];
}
}
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse
{
return ([self isCancelled] || [self shouldCancel]) ? nil : cachedResponse;
}
- (void)connection:(NSURLConnection *)connection
didSendBodyData:(NSInteger)bytesWritten
totalBytesWritten:(NSInteger)totalBytesWritten
totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite
{
if (![self isCancelled] && ![self isFinished])
{
if ([self shouldCancel])
{
[self cancelFromRunLoop];
}
else
{
if ([_delegate respondsToSelector:@selector(connectionOperation:didSendBodyData:totalBytesWritten:totalBytesExpectedToWrite:)])
{
[_delegate connectionOperation:self
didSendBodyData:(NSUInteger)bytesWritten
totalBytesWritten:(NSUInteger)totalBytesWritten
totalBytesExpectedToWrite:totalBytesExpectedToWrite];
}
}
}
}
- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
BOOL handledAuth = NO;
if ([self allowsUntrustedServerCertificates] &&
[[[challenge protectionSpace] authenticationMethod] isEqualToString:NSURLAuthenticationMethodServerTrust] &&
[challenge previousFailureCount] == 0 &&
[challenge proposedCredential] == nil)
{
[[challenge sender] useCredential:[NSURLCredential credentialForTrust:[[challenge protectionSpace] serverTrust]]
forAuthenticationChallenge:challenge];
handledAuth = YES;
}
if (!handledAuth)
{
if ([[challenge sender] respondsToSelector:@selector(performDefaultHandlingForAuthenticationChallenge:)])
{
[[challenge sender] performDefaultHandlingForAuthenticationChallenge:challenge];
}
else
{
[[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge];
}
}
}
@end