AFURLConnectionOperation.m 27 KB

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