AFURLConnectionOperation.m 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792
  1. // AFURLConnectionOperation.m
  2. // Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. #import "AFURLConnectionOperation.h"
  22. #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
  23. #import <UIKit/UIKit.h>
  24. #endif
  25. #if !__has_feature(objc_arc)
  26. #error AFNetworking must be built with ARC.
  27. // You can turn on ARC for only AFNetworking files by adding -fobjc-arc to the build phase for each of its files.
  28. #endif
  29. typedef NS_ENUM(NSInteger, AFOperationState) {
  30. AFOperationPausedState = -1,
  31. AFOperationReadyState = 1,
  32. AFOperationExecutingState = 2,
  33. AFOperationFinishedState = 3,
  34. };
  35. static dispatch_group_t url_request_operation_completion_group() {
  36. static dispatch_group_t af_url_request_operation_completion_group;
  37. static dispatch_once_t onceToken;
  38. dispatch_once(&onceToken, ^{
  39. af_url_request_operation_completion_group = dispatch_group_create();
  40. });
  41. return af_url_request_operation_completion_group;
  42. }
  43. static dispatch_queue_t url_request_operation_completion_queue() {
  44. static dispatch_queue_t af_url_request_operation_completion_queue;
  45. static dispatch_once_t onceToken;
  46. dispatch_once(&onceToken, ^{
  47. af_url_request_operation_completion_queue = dispatch_queue_create("com.alamofire.networking.operation.queue", DISPATCH_QUEUE_CONCURRENT );
  48. });
  49. return af_url_request_operation_completion_queue;
  50. }
  51. static NSString * const kAFNetworkingLockName = @"com.alamofire.networking.operation.lock";
  52. NSString * const AFNetworkingOperationDidStartNotification = @"com.alamofire.networking.operation.start";
  53. NSString * const AFNetworkingOperationDidFinishNotification = @"com.alamofire.networking.operation.finish";
  54. typedef void (^AFURLConnectionOperationProgressBlock)(NSUInteger bytes, long long totalBytes, long long totalBytesExpected);
  55. typedef void (^AFURLConnectionOperationAuthenticationChallengeBlock)(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge);
  56. typedef NSCachedURLResponse * (^AFURLConnectionOperationCacheResponseBlock)(NSURLConnection *connection, NSCachedURLResponse *cachedResponse);
  57. typedef NSURLRequest * (^AFURLConnectionOperationRedirectResponseBlock)(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse);
  58. typedef void (^AFURLConnectionOperationBackgroundTaskCleanupBlock)();
  59. static inline NSString * AFKeyPathFromOperationState(AFOperationState state) {
  60. switch (state) {
  61. case AFOperationReadyState:
  62. return @"isReady";
  63. case AFOperationExecutingState:
  64. return @"isExecuting";
  65. case AFOperationFinishedState:
  66. return @"isFinished";
  67. case AFOperationPausedState:
  68. return @"isPaused";
  69. default: {
  70. #pragma clang diagnostic push
  71. #pragma clang diagnostic ignored "-Wunreachable-code"
  72. return @"state";
  73. #pragma clang diagnostic pop
  74. }
  75. }
  76. }
  77. static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperationState toState, BOOL isCancelled) {
  78. switch (fromState) {
  79. case AFOperationReadyState:
  80. switch (toState) {
  81. case AFOperationPausedState:
  82. case AFOperationExecutingState:
  83. return YES;
  84. case AFOperationFinishedState:
  85. return isCancelled;
  86. default:
  87. return NO;
  88. }
  89. case AFOperationExecutingState:
  90. switch (toState) {
  91. case AFOperationPausedState:
  92. case AFOperationFinishedState:
  93. return YES;
  94. default:
  95. return NO;
  96. }
  97. case AFOperationFinishedState:
  98. return NO;
  99. case AFOperationPausedState:
  100. return toState == AFOperationReadyState;
  101. default: {
  102. #pragma clang diagnostic push
  103. #pragma clang diagnostic ignored "-Wunreachable-code"
  104. switch (toState) {
  105. case AFOperationPausedState:
  106. case AFOperationReadyState:
  107. case AFOperationExecutingState:
  108. case AFOperationFinishedState:
  109. return YES;
  110. default:
  111. return NO;
  112. }
  113. }
  114. #pragma clang diagnostic pop
  115. }
  116. }
  117. @interface AFURLConnectionOperation ()
  118. @property (readwrite, nonatomic, assign) AFOperationState state;
  119. @property (readwrite, nonatomic, strong) NSRecursiveLock *lock;
  120. @property (readwrite, nonatomic, strong) NSURLConnection *connection;
  121. @property (readwrite, nonatomic, strong) NSURLRequest *request;
  122. @property (readwrite, nonatomic, strong) NSURLResponse *response;
  123. @property (readwrite, nonatomic, strong) NSError *error;
  124. @property (readwrite, nonatomic, strong) NSData *responseData;
  125. @property (readwrite, nonatomic, copy) NSString *responseString;
  126. @property (readwrite, nonatomic, assign) NSStringEncoding responseStringEncoding;
  127. @property (readwrite, nonatomic, assign) long long totalBytesRead;
  128. @property (readwrite, nonatomic, copy) AFURLConnectionOperationBackgroundTaskCleanupBlock backgroundTaskCleanup;
  129. @property (readwrite, nonatomic, copy) AFURLConnectionOperationProgressBlock uploadProgress;
  130. @property (readwrite, nonatomic, copy) AFURLConnectionOperationProgressBlock downloadProgress;
  131. @property (readwrite, nonatomic, copy) AFURLConnectionOperationAuthenticationChallengeBlock authenticationChallenge;
  132. @property (readwrite, nonatomic, copy) AFURLConnectionOperationCacheResponseBlock cacheResponse;
  133. @property (readwrite, nonatomic, copy) AFURLConnectionOperationRedirectResponseBlock redirectResponse;
  134. - (void)operationDidStart;
  135. - (void)finish;
  136. - (void)cancelConnection;
  137. @end
  138. @implementation AFURLConnectionOperation
  139. @synthesize outputStream = _outputStream;
  140. + (void)networkRequestThreadEntryPoint:(id)__unused object {
  141. @autoreleasepool {
  142. [[NSThread currentThread] setName:@"AFNetworking"];
  143. NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
  144. [runLoop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode];
  145. [runLoop run];
  146. }
  147. }
  148. + (NSThread *)networkRequestThread {
  149. static NSThread *_networkRequestThread = nil;
  150. static dispatch_once_t oncePredicate;
  151. dispatch_once(&oncePredicate, ^{
  152. _networkRequestThread = [[NSThread alloc] initWithTarget:self selector:@selector(networkRequestThreadEntryPoint:) object:nil];
  153. [_networkRequestThread start];
  154. });
  155. return _networkRequestThread;
  156. }
  157. - (instancetype)initWithRequest:(NSURLRequest *)urlRequest {
  158. NSParameterAssert(urlRequest);
  159. self = [super init];
  160. if (!self) {
  161. return nil;
  162. }
  163. _state = AFOperationReadyState;
  164. self.lock = [[NSRecursiveLock alloc] init];
  165. self.lock.name = kAFNetworkingLockName;
  166. self.runLoopModes = [NSSet setWithObject:NSRunLoopCommonModes];
  167. self.request = urlRequest;
  168. self.shouldUseCredentialStorage = YES;
  169. self.securityPolicy = [AFSecurityPolicy defaultPolicy];
  170. return self;
  171. }
  172. - (instancetype)init NS_UNAVAILABLE
  173. {
  174. return nil;
  175. }
  176. - (void)dealloc {
  177. if (_outputStream) {
  178. [_outputStream close];
  179. _outputStream = nil;
  180. }
  181. if (_backgroundTaskCleanup) {
  182. _backgroundTaskCleanup();
  183. }
  184. }
  185. #pragma mark -
  186. - (void)setResponseData:(NSData *)responseData {
  187. [self.lock lock];
  188. if (!responseData) {
  189. _responseData = nil;
  190. } else {
  191. _responseData = [NSData dataWithBytes:responseData.bytes length:responseData.length];
  192. }
  193. [self.lock unlock];
  194. }
  195. - (NSString *)responseString {
  196. [self.lock lock];
  197. if (!_responseString && self.response && self.responseData) {
  198. self.responseString = [[NSString alloc] initWithData:self.responseData encoding:self.responseStringEncoding];
  199. }
  200. [self.lock unlock];
  201. return _responseString;
  202. }
  203. - (NSStringEncoding)responseStringEncoding {
  204. [self.lock lock];
  205. if (!_responseStringEncoding && self.response) {
  206. NSStringEncoding stringEncoding = NSUTF8StringEncoding;
  207. if (self.response.textEncodingName) {
  208. CFStringEncoding IANAEncoding = CFStringConvertIANACharSetNameToEncoding((__bridge CFStringRef)self.response.textEncodingName);
  209. if (IANAEncoding != kCFStringEncodingInvalidId) {
  210. stringEncoding = CFStringConvertEncodingToNSStringEncoding(IANAEncoding);
  211. }
  212. }
  213. self.responseStringEncoding = stringEncoding;
  214. }
  215. [self.lock unlock];
  216. return _responseStringEncoding;
  217. }
  218. - (NSInputStream *)inputStream {
  219. return self.request.HTTPBodyStream;
  220. }
  221. - (void)setInputStream:(NSInputStream *)inputStream {
  222. NSMutableURLRequest *mutableRequest = [self.request mutableCopy];
  223. mutableRequest.HTTPBodyStream = inputStream;
  224. self.request = mutableRequest;
  225. }
  226. - (NSOutputStream *)outputStream {
  227. if (!_outputStream) {
  228. self.outputStream = [NSOutputStream outputStreamToMemory];
  229. }
  230. return _outputStream;
  231. }
  232. - (void)setOutputStream:(NSOutputStream *)outputStream {
  233. [self.lock lock];
  234. if (outputStream != _outputStream) {
  235. if (_outputStream) {
  236. [_outputStream close];
  237. }
  238. _outputStream = outputStream;
  239. }
  240. [self.lock unlock];
  241. }
  242. #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
  243. - (void)setShouldExecuteAsBackgroundTaskWithExpirationHandler:(void (^)(void))handler {
  244. [self.lock lock];
  245. if (!self.backgroundTaskCleanup) {
  246. UIApplication *application = [UIApplication sharedApplication];
  247. UIBackgroundTaskIdentifier __block backgroundTaskIdentifier = UIBackgroundTaskInvalid;
  248. __weak __typeof(self)weakSelf = self;
  249. self.backgroundTaskCleanup = ^(){
  250. if (backgroundTaskIdentifier != UIBackgroundTaskInvalid) {
  251. [[UIApplication sharedApplication] endBackgroundTask:backgroundTaskIdentifier];
  252. backgroundTaskIdentifier = UIBackgroundTaskInvalid;
  253. }
  254. };
  255. backgroundTaskIdentifier = [application beginBackgroundTaskWithExpirationHandler:^{
  256. __strong __typeof(weakSelf)strongSelf = weakSelf;
  257. if (handler) {
  258. handler();
  259. }
  260. if (strongSelf) {
  261. [strongSelf cancel];
  262. strongSelf.backgroundTaskCleanup();
  263. }
  264. }];
  265. }
  266. [self.lock unlock];
  267. }
  268. #endif
  269. #pragma mark -
  270. - (void)setState:(AFOperationState)state {
  271. if (!AFStateTransitionIsValid(self.state, state, [self isCancelled])) {
  272. return;
  273. }
  274. [self.lock lock];
  275. NSString *oldStateKey = AFKeyPathFromOperationState(self.state);
  276. NSString *newStateKey = AFKeyPathFromOperationState(state);
  277. [self willChangeValueForKey:newStateKey];
  278. [self willChangeValueForKey:oldStateKey];
  279. _state = state;
  280. [self didChangeValueForKey:oldStateKey];
  281. [self didChangeValueForKey:newStateKey];
  282. [self.lock unlock];
  283. }
  284. - (void)pause {
  285. if ([self isPaused] || [self isFinished] || [self isCancelled]) {
  286. return;
  287. }
  288. [self.lock lock];
  289. if ([self isExecuting]) {
  290. [self performSelector:@selector(operationDidPause) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]];
  291. dispatch_async(dispatch_get_main_queue(), ^{
  292. NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
  293. [notificationCenter postNotificationName:AFNetworkingOperationDidFinishNotification object:self];
  294. });
  295. }
  296. self.state = AFOperationPausedState;
  297. [self.lock unlock];
  298. }
  299. - (void)operationDidPause {
  300. [self.lock lock];
  301. [self.connection cancel];
  302. [self.lock unlock];
  303. }
  304. - (BOOL)isPaused {
  305. return self.state == AFOperationPausedState;
  306. }
  307. - (void)resume {
  308. if (![self isPaused]) {
  309. return;
  310. }
  311. [self.lock lock];
  312. self.state = AFOperationReadyState;
  313. [self start];
  314. [self.lock unlock];
  315. }
  316. #pragma mark -
  317. - (void)setUploadProgressBlock:(void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))block {
  318. self.uploadProgress = block;
  319. }
  320. - (void)setDownloadProgressBlock:(void (^)(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead))block {
  321. self.downloadProgress = block;
  322. }
  323. - (void)setWillSendRequestForAuthenticationChallengeBlock:(void (^)(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge))block {
  324. self.authenticationChallenge = block;
  325. }
  326. - (void)setCacheResponseBlock:(NSCachedURLResponse * (^)(NSURLConnection *connection, NSCachedURLResponse *cachedResponse))block {
  327. self.cacheResponse = block;
  328. }
  329. - (void)setRedirectResponseBlock:(NSURLRequest * (^)(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse))block {
  330. self.redirectResponse = block;
  331. }
  332. #pragma mark - NSOperation
  333. - (void)setCompletionBlock:(void (^)(void))block {
  334. [self.lock lock];
  335. if (!block) {
  336. [super setCompletionBlock:nil];
  337. } else {
  338. __weak __typeof(self)weakSelf = self;
  339. [super setCompletionBlock:^ {
  340. __strong __typeof(weakSelf)strongSelf = weakSelf;
  341. #pragma clang diagnostic push
  342. #pragma clang diagnostic ignored "-Wgnu"
  343. dispatch_group_t group = strongSelf.completionGroup ?: url_request_operation_completion_group();
  344. dispatch_queue_t queue = strongSelf.completionQueue ?: dispatch_get_main_queue();
  345. #pragma clang diagnostic pop
  346. dispatch_group_async(group, queue, ^{
  347. block();
  348. });
  349. dispatch_group_notify(group, url_request_operation_completion_queue(), ^{
  350. [strongSelf setCompletionBlock:nil];
  351. });
  352. }];
  353. }
  354. [self.lock unlock];
  355. }
  356. - (BOOL)isReady {
  357. return self.state == AFOperationReadyState && [super isReady];
  358. }
  359. - (BOOL)isExecuting {
  360. return self.state == AFOperationExecutingState;
  361. }
  362. - (BOOL)isFinished {
  363. return self.state == AFOperationFinishedState;
  364. }
  365. - (BOOL)isConcurrent {
  366. return YES;
  367. }
  368. - (void)start {
  369. [self.lock lock];
  370. if ([self isCancelled]) {
  371. [self performSelector:@selector(cancelConnection) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]];
  372. } else if ([self isReady]) {
  373. self.state = AFOperationExecutingState;
  374. [self performSelector:@selector(operationDidStart) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]];
  375. }
  376. [self.lock unlock];
  377. }
  378. - (void)operationDidStart {
  379. [self.lock lock];
  380. if (![self isCancelled]) {
  381. self.connection = [[NSURLConnection alloc] initWithRequest:self.request delegate:self startImmediately:NO];
  382. NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
  383. for (NSString *runLoopMode in self.runLoopModes) {
  384. [self.connection scheduleInRunLoop:runLoop forMode:runLoopMode];
  385. [self.outputStream scheduleInRunLoop:runLoop forMode:runLoopMode];
  386. }
  387. [self.outputStream open];
  388. [self.connection start];
  389. }
  390. [self.lock unlock];
  391. dispatch_async(dispatch_get_main_queue(), ^{
  392. [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingOperationDidStartNotification object:self];
  393. });
  394. }
  395. - (void)finish {
  396. [self.lock lock];
  397. self.state = AFOperationFinishedState;
  398. [self.lock unlock];
  399. dispatch_async(dispatch_get_main_queue(), ^{
  400. [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingOperationDidFinishNotification object:self];
  401. });
  402. }
  403. - (void)cancel {
  404. [self.lock lock];
  405. if (![self isFinished] && ![self isCancelled]) {
  406. [super cancel];
  407. if ([self isExecuting]) {
  408. [self performSelector:@selector(cancelConnection) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]];
  409. }
  410. }
  411. [self.lock unlock];
  412. }
  413. - (void)cancelConnection {
  414. NSDictionary *userInfo = nil;
  415. if ([self.request URL]) {
  416. userInfo = @{NSURLErrorFailingURLErrorKey : [self.request URL]};
  417. }
  418. NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCancelled userInfo:userInfo];
  419. if (![self isFinished]) {
  420. if (self.connection) {
  421. [self.connection cancel];
  422. [self performSelector:@selector(connection:didFailWithError:) withObject:self.connection withObject:error];
  423. } else {
  424. // Accommodate race condition where `self.connection` has not yet been set before cancellation
  425. self.error = error;
  426. [self finish];
  427. }
  428. }
  429. }
  430. #pragma mark -
  431. + (NSArray *)batchOfRequestOperations:(NSArray *)operations
  432. progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock
  433. completionBlock:(void (^)(NSArray *operations))completionBlock
  434. {
  435. if (!operations || [operations count] == 0) {
  436. return @[[NSBlockOperation blockOperationWithBlock:^{
  437. dispatch_async(dispatch_get_main_queue(), ^{
  438. if (completionBlock) {
  439. completionBlock(@[]);
  440. }
  441. });
  442. }]];
  443. }
  444. __block dispatch_group_t group = dispatch_group_create();
  445. NSBlockOperation *batchedOperation = [NSBlockOperation blockOperationWithBlock:^{
  446. dispatch_group_notify(group, dispatch_get_main_queue(), ^{
  447. if (completionBlock) {
  448. completionBlock(operations);
  449. }
  450. });
  451. }];
  452. for (AFURLConnectionOperation *operation in operations) {
  453. operation.completionGroup = group;
  454. void (^originalCompletionBlock)(void) = [operation.completionBlock copy];
  455. __weak __typeof(operation)weakOperation = operation;
  456. operation.completionBlock = ^{
  457. __strong __typeof(weakOperation)strongOperation = weakOperation;
  458. #pragma clang diagnostic push
  459. #pragma clang diagnostic ignored "-Wgnu"
  460. dispatch_queue_t queue = strongOperation.completionQueue ?: dispatch_get_main_queue();
  461. #pragma clang diagnostic pop
  462. dispatch_group_async(group, queue, ^{
  463. if (originalCompletionBlock) {
  464. originalCompletionBlock();
  465. }
  466. NSUInteger numberOfFinishedOperations = [[operations indexesOfObjectsPassingTest:^BOOL(id op, NSUInteger __unused idx, BOOL __unused *stop) {
  467. return [op isFinished];
  468. }] count];
  469. if (progressBlock) {
  470. progressBlock(numberOfFinishedOperations, [operations count]);
  471. }
  472. dispatch_group_leave(group);
  473. });
  474. };
  475. dispatch_group_enter(group);
  476. [batchedOperation addDependency:operation];
  477. }
  478. return [operations arrayByAddingObject:batchedOperation];
  479. }
  480. #pragma mark - NSObject
  481. - (NSString *)description {
  482. [self.lock lock];
  483. NSString *description = [NSString stringWithFormat:@"<%@: %p, state: %@, cancelled: %@ request: %@, response: %@>", NSStringFromClass([self class]), self, AFKeyPathFromOperationState(self.state), ([self isCancelled] ? @"YES" : @"NO"), self.request, self.response];
  484. [self.lock unlock];
  485. return description;
  486. }
  487. #pragma mark - NSURLConnectionDelegate
  488. - (void)connection:(NSURLConnection *)connection
  489. willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
  490. {
  491. if (self.authenticationChallenge) {
  492. self.authenticationChallenge(connection, challenge);
  493. return;
  494. }
  495. if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
  496. if ([self.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:challenge.protectionSpace.host]) {
  497. NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
  498. [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
  499. } else {
  500. [[challenge sender] cancelAuthenticationChallenge:challenge];
  501. }
  502. } else {
  503. if ([challenge previousFailureCount] == 0) {
  504. if (self.credential) {
  505. [[challenge sender] useCredential:self.credential forAuthenticationChallenge:challenge];
  506. } else {
  507. [[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge];
  508. }
  509. } else {
  510. [[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge];
  511. }
  512. }
  513. }
  514. - (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection __unused *)connection {
  515. return self.shouldUseCredentialStorage;
  516. }
  517. - (NSURLRequest *)connection:(NSURLConnection *)connection
  518. willSendRequest:(NSURLRequest *)request
  519. redirectResponse:(NSURLResponse *)redirectResponse
  520. {
  521. if (self.redirectResponse) {
  522. return self.redirectResponse(connection, request, redirectResponse);
  523. } else {
  524. return request;
  525. }
  526. }
  527. - (void)connection:(NSURLConnection __unused *)connection
  528. didSendBodyData:(NSInteger)bytesWritten
  529. totalBytesWritten:(NSInteger)totalBytesWritten
  530. totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite
  531. {
  532. dispatch_async(dispatch_get_main_queue(), ^{
  533. if (self.uploadProgress) {
  534. self.uploadProgress((NSUInteger)bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
  535. }
  536. });
  537. }
  538. - (void)connection:(NSURLConnection __unused *)connection
  539. didReceiveResponse:(NSURLResponse *)response
  540. {
  541. self.response = response;
  542. }
  543. - (void)connection:(NSURLConnection __unused *)connection
  544. didReceiveData:(NSData *)data
  545. {
  546. NSUInteger length = [data length];
  547. while (YES) {
  548. NSInteger totalNumberOfBytesWritten = 0;
  549. if ([self.outputStream hasSpaceAvailable]) {
  550. const uint8_t *dataBuffer = (uint8_t *)[data bytes];
  551. NSInteger numberOfBytesWritten = 0;
  552. while (totalNumberOfBytesWritten < (NSInteger)length) {
  553. numberOfBytesWritten = [self.outputStream write:&dataBuffer[(NSUInteger)totalNumberOfBytesWritten] maxLength:(length - (NSUInteger)totalNumberOfBytesWritten)];
  554. if (numberOfBytesWritten == -1) {
  555. break;
  556. }
  557. totalNumberOfBytesWritten += numberOfBytesWritten;
  558. }
  559. break;
  560. } else {
  561. [self.connection cancel];
  562. if (self.outputStream.streamError) {
  563. [self performSelector:@selector(connection:didFailWithError:) withObject:self.connection withObject:self.outputStream.streamError];
  564. }
  565. return;
  566. }
  567. }
  568. dispatch_async(dispatch_get_main_queue(), ^{
  569. self.totalBytesRead += (long long)length;
  570. if (self.downloadProgress) {
  571. self.downloadProgress(length, self.totalBytesRead, self.response.expectedContentLength);
  572. }
  573. });
  574. }
  575. - (void)connectionDidFinishLoading:(NSURLConnection __unused *)connection {
  576. self.responseData = [self.outputStream propertyForKey:NSStreamDataWrittenToMemoryStreamKey];
  577. [self.outputStream close];
  578. if (self.responseData) {
  579. self.outputStream = nil;
  580. }
  581. self.connection = nil;
  582. [self finish];
  583. }
  584. - (void)connection:(NSURLConnection __unused *)connection
  585. didFailWithError:(NSError *)error
  586. {
  587. self.error = error;
  588. [self.outputStream close];
  589. if (self.responseData) {
  590. self.outputStream = nil;
  591. }
  592. self.connection = nil;
  593. [self finish];
  594. }
  595. - (NSCachedURLResponse *)connection:(NSURLConnection *)connection
  596. willCacheResponse:(NSCachedURLResponse *)cachedResponse
  597. {
  598. if (self.cacheResponse) {
  599. return self.cacheResponse(connection, cachedResponse);
  600. } else {
  601. if ([self isCancelled]) {
  602. return nil;
  603. }
  604. return cachedResponse;
  605. }
  606. }
  607. #pragma mark - NSSecureCoding
  608. + (BOOL)supportsSecureCoding {
  609. return YES;
  610. }
  611. - (id)initWithCoder:(NSCoder *)decoder {
  612. NSURLRequest *request = [decoder decodeObjectOfClass:[NSURLRequest class] forKey:NSStringFromSelector(@selector(request))];
  613. self = [self initWithRequest:request];
  614. if (!self) {
  615. return nil;
  616. }
  617. self.state = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(state))] integerValue];
  618. self.response = [decoder decodeObjectOfClass:[NSHTTPURLResponse class] forKey:NSStringFromSelector(@selector(response))];
  619. self.error = [decoder decodeObjectOfClass:[NSError class] forKey:NSStringFromSelector(@selector(error))];
  620. self.responseData = [decoder decodeObjectOfClass:[NSData class] forKey:NSStringFromSelector(@selector(responseData))];
  621. self.totalBytesRead = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(totalBytesRead))] longLongValue];
  622. return self;
  623. }
  624. - (void)encodeWithCoder:(NSCoder *)coder {
  625. [self pause];
  626. [coder encodeObject:self.request forKey:NSStringFromSelector(@selector(request))];
  627. switch (self.state) {
  628. case AFOperationExecutingState:
  629. case AFOperationPausedState:
  630. [coder encodeInteger:AFOperationReadyState forKey:NSStringFromSelector(@selector(state))];
  631. break;
  632. default:
  633. [coder encodeInteger:self.state forKey:NSStringFromSelector(@selector(state))];
  634. break;
  635. }
  636. [coder encodeObject:self.response forKey:NSStringFromSelector(@selector(response))];
  637. [coder encodeObject:self.error forKey:NSStringFromSelector(@selector(error))];
  638. [coder encodeObject:self.responseData forKey:NSStringFromSelector(@selector(responseData))];
  639. [coder encodeInt64:self.totalBytesRead forKey:NSStringFromSelector(@selector(totalBytesRead))];
  640. }
  641. #pragma mark - NSCopying
  642. - (id)copyWithZone:(NSZone *)zone {
  643. AFURLConnectionOperation *operation = [(AFURLConnectionOperation *)[[self class] allocWithZone:zone] initWithRequest:self.request];
  644. operation.uploadProgress = self.uploadProgress;
  645. operation.downloadProgress = self.downloadProgress;
  646. operation.authenticationChallenge = self.authenticationChallenge;
  647. operation.cacheResponse = self.cacheResponse;
  648. operation.redirectResponse = self.redirectResponse;
  649. operation.completionQueue = self.completionQueue;
  650. operation.completionGroup = self.completionGroup;
  651. return operation;
  652. }
  653. @end