AFURLConnectionOperation.m 27 KB

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