JAHPQNSURLSessionDemux.m 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. /*
  2. File: JAHPQNSURLSessionDemux.m
  3. Abstract: A general class to demux NSURLSession delegate callbacks.
  4. Version: 1.1
  5. Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple
  6. Inc. ("Apple") in consideration of your agreement to the following
  7. terms, and your use, installation, modification or redistribution of
  8. this Apple software constitutes acceptance of these terms. If you do
  9. not agree with these terms, please do not use, install, modify or
  10. redistribute this Apple software.
  11. In consideration of your agreement to abide by the following terms, and
  12. subject to these terms, Apple grants you a personal, non-exclusive
  13. license, under Apple's copyrights in this original Apple software (the
  14. "Apple Software"), to use, reproduce, modify and redistribute the Apple
  15. Software, with or without modifications, in source and/or binary forms;
  16. provided that if you redistribute the Apple Software in its entirety and
  17. without modifications, you must retain this notice and the following
  18. text and disclaimers in all such redistributions of the Apple Software.
  19. Neither the name, trademarks, service marks or logos of Apple Inc. may
  20. be used to endorse or promote products derived from the Apple Software
  21. without specific prior written permission from Apple. Except as
  22. expressly stated in this notice, no other rights or licenses, express or
  23. implied, are granted by Apple herein, including but not limited to any
  24. patent rights that may be infringed by your derivative works or by other
  25. works in which the Apple Software may be incorporated.
  26. The Apple Software is provided by Apple on an "AS IS" basis. APPLE
  27. MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
  28. THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS
  29. FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
  30. OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
  31. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
  32. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  33. SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  34. INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,
  35. MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED
  36. AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
  37. STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
  38. POSSIBILITY OF SUCH DAMAGE.
  39. Copyright (C) 2014 Apple Inc. All Rights Reserved.
  40. */
  41. #import "JAHPQNSURLSessionDemux.h"
  42. @interface JAHPQNSURLSessionDemuxTaskInfo : NSObject
  43. - (instancetype)initWithTask:(NSURLSessionDataTask *)task delegate:(id<NSURLSessionDataDelegate>)delegate modes:(NSArray *)modes;
  44. @property (atomic, strong, readonly ) NSURLSessionDataTask * task;
  45. @property (atomic, strong, readonly ) id<NSURLSessionDataDelegate> delegate;
  46. @property (atomic, strong, readonly ) NSThread * thread;
  47. @property (atomic, copy, readonly ) NSArray * modes;
  48. - (void)performBlock:(dispatch_block_t)block;
  49. - (void)invalidate;
  50. @end
  51. @interface JAHPQNSURLSessionDemuxTaskInfo ()
  52. @property (atomic, strong, readwrite) id<NSURLSessionDataDelegate> delegate;
  53. @property (atomic, strong, readwrite) NSThread * thread;
  54. @end
  55. @implementation JAHPQNSURLSessionDemuxTaskInfo
  56. - (instancetype)initWithTask:(NSURLSessionDataTask *)task delegate:(id<NSURLSessionDataDelegate>)delegate modes:(NSArray *)modes
  57. {
  58. assert(task != nil);
  59. assert(delegate != nil);
  60. assert(modes != nil);
  61. self = [super init];
  62. if (self != nil) {
  63. self->_task = task;
  64. self->_delegate = delegate;
  65. self->_thread = [NSThread currentThread];
  66. self->_modes = [modes copy];
  67. }
  68. return self;
  69. }
  70. - (void)performBlock:(dispatch_block_t)block
  71. {
  72. assert(self.delegate != nil);
  73. assert(self.thread != nil);
  74. [self performSelector:@selector(performBlockOnClientThread:) onThread:self.thread withObject:[block copy] waitUntilDone:NO modes:self.modes];
  75. }
  76. - (void)performBlockOnClientThread:(dispatch_block_t)block
  77. {
  78. assert([NSThread currentThread] == self.thread);
  79. block();
  80. }
  81. - (void)invalidate
  82. {
  83. self.delegate = nil;
  84. self.thread = nil;
  85. }
  86. @end
  87. @interface JAHPQNSURLSessionDemux () <NSURLSessionDataDelegate>
  88. @property (atomic, strong, readonly ) NSMutableDictionary * taskInfoByTaskID; // keys NSURLSessionTask taskIdentifier, values are SessionManager
  89. @property (atomic, strong, readonly ) NSOperationQueue * sessionDelegateQueue;
  90. @end
  91. @implementation JAHPQNSURLSessionDemux
  92. - (instancetype)init
  93. {
  94. return [self initWithConfiguration:nil];
  95. }
  96. - (instancetype)initWithConfiguration:(NSURLSessionConfiguration *)configuration
  97. {
  98. // configuration may be nil
  99. self = [super init];
  100. if (self != nil) {
  101. if (configuration == nil) {
  102. configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  103. }
  104. self->_configuration = [configuration copy];
  105. self->_taskInfoByTaskID = [[NSMutableDictionary alloc] init];
  106. self->_sessionDelegateQueue = [[NSOperationQueue alloc] init];
  107. [self->_sessionDelegateQueue setMaxConcurrentOperationCount:1];
  108. [self->_sessionDelegateQueue setName:@"JAHPQNSURLSessionDemux"];
  109. self->_session = [NSURLSession sessionWithConfiguration:self->_configuration delegate:self delegateQueue:self->_sessionDelegateQueue];
  110. self->_session.sessionDescription = @"JAHPQNSURLSessionDemux";
  111. }
  112. return self;
  113. }
  114. - (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request delegate:(id<NSURLSessionDataDelegate>)delegate modes:(NSArray *)modes
  115. {
  116. NSURLSessionDataTask * task;
  117. JAHPQNSURLSessionDemuxTaskInfo * taskInfo;
  118. assert(request != nil);
  119. assert(delegate != nil);
  120. // modes may be nil
  121. if ([modes count] == 0) {
  122. modes = @[ NSDefaultRunLoopMode ];
  123. }
  124. task = [self.session dataTaskWithRequest:request];
  125. assert(task != nil);
  126. taskInfo = [[JAHPQNSURLSessionDemuxTaskInfo alloc] initWithTask:task delegate:delegate modes:modes];
  127. @synchronized (self) {
  128. self.taskInfoByTaskID[@(task.taskIdentifier)] = taskInfo;
  129. }
  130. return task;
  131. }
  132. - (JAHPQNSURLSessionDemuxTaskInfo *)taskInfoForTask:(NSURLSessionTask *)task
  133. {
  134. JAHPQNSURLSessionDemuxTaskInfo * result;
  135. assert(task != nil);
  136. @synchronized (self) {
  137. result = self.taskInfoByTaskID[@(task.taskIdentifier)];
  138. assert(result != nil);
  139. }
  140. return result;
  141. }
  142. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)newRequest completionHandler:(void (^)(NSURLRequest *))completionHandler
  143. {
  144. JAHPQNSURLSessionDemuxTaskInfo * taskInfo;
  145. taskInfo = [self taskInfoForTask:task];
  146. if ([taskInfo.delegate respondsToSelector:@selector(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:)]) {
  147. [taskInfo performBlock:^{
  148. [taskInfo.delegate URLSession:session task:task willPerformHTTPRedirection:response newRequest:newRequest completionHandler:completionHandler];
  149. }];
  150. } else {
  151. completionHandler(newRequest);
  152. }
  153. }
  154. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
  155. {
  156. JAHPQNSURLSessionDemuxTaskInfo * taskInfo;
  157. taskInfo = [self taskInfoForTask:task];
  158. if ([taskInfo.delegate respondsToSelector:@selector(URLSession:task:didReceiveChallenge:completionHandler:)]) {
  159. [taskInfo performBlock:^{
  160. [taskInfo.delegate URLSession:session task:task didReceiveChallenge:challenge completionHandler:completionHandler];
  161. }];
  162. } else {
  163. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
  164. }
  165. }
  166. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task needNewBodyStream:(void (^)(NSInputStream *bodyStream))completionHandler
  167. {
  168. JAHPQNSURLSessionDemuxTaskInfo * taskInfo;
  169. taskInfo = [self taskInfoForTask:task];
  170. if ([taskInfo.delegate respondsToSelector:@selector(URLSession:task:needNewBodyStream:)]) {
  171. [taskInfo performBlock:^{
  172. [taskInfo.delegate URLSession:session task:task needNewBodyStream:completionHandler];
  173. }];
  174. } else {
  175. completionHandler(nil);
  176. }
  177. }
  178. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend
  179. {
  180. JAHPQNSURLSessionDemuxTaskInfo * taskInfo;
  181. taskInfo = [self taskInfoForTask:task];
  182. if ([taskInfo.delegate respondsToSelector:@selector(URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)]) {
  183. [taskInfo performBlock:^{
  184. [taskInfo.delegate URLSession:session task:task didSendBodyData:bytesSent totalBytesSent:totalBytesSent totalBytesExpectedToSend:totalBytesExpectedToSend];
  185. }];
  186. }
  187. }
  188. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
  189. {
  190. JAHPQNSURLSessionDemuxTaskInfo * taskInfo;
  191. taskInfo = [self taskInfoForTask:task];
  192. // This is our last delegate callback so we remove our task info record.
  193. @synchronized (self) {
  194. [self.taskInfoByTaskID removeObjectForKey:@(taskInfo.task.taskIdentifier)];
  195. }
  196. // Call the delegate if required. In that case we invalidate the task info on the client thread
  197. // after calling the delegate, otherwise the client thread side of the -performBlock: code can
  198. // find itself with an invalidated task info.
  199. if ([taskInfo.delegate respondsToSelector:@selector(URLSession:task:didCompleteWithError:)]) {
  200. [taskInfo performBlock:^{
  201. [taskInfo.delegate URLSession:session task:task didCompleteWithError:error];
  202. [taskInfo invalidate];
  203. }];
  204. } else {
  205. [taskInfo invalidate];
  206. }
  207. }
  208. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler
  209. {
  210. JAHPQNSURLSessionDemuxTaskInfo * taskInfo;
  211. taskInfo = [self taskInfoForTask:dataTask];
  212. if ([taskInfo.delegate respondsToSelector:@selector(URLSession:dataTask:didReceiveResponse:completionHandler:)]) {
  213. [taskInfo performBlock:^{
  214. [taskInfo.delegate URLSession:session dataTask:dataTask didReceiveResponse:response completionHandler:completionHandler];
  215. }];
  216. } else {
  217. completionHandler(NSURLSessionResponseAllow);
  218. }
  219. }
  220. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didBecomeDownloadTask:(NSURLSessionDownloadTask *)downloadTask
  221. {
  222. JAHPQNSURLSessionDemuxTaskInfo * taskInfo;
  223. taskInfo = [self taskInfoForTask:dataTask];
  224. if ([taskInfo.delegate respondsToSelector:@selector(URLSession:dataTask:didBecomeDownloadTask:)]) {
  225. [taskInfo performBlock:^{
  226. [taskInfo.delegate URLSession:session dataTask:dataTask didBecomeDownloadTask:downloadTask];
  227. }];
  228. }
  229. }
  230. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
  231. {
  232. JAHPQNSURLSessionDemuxTaskInfo * taskInfo;
  233. taskInfo = [self taskInfoForTask:dataTask];
  234. if ([taskInfo.delegate respondsToSelector:@selector(URLSession:dataTask:didReceiveData:)]) {
  235. [taskInfo performBlock:^{
  236. [taskInfo.delegate URLSession:session dataTask:dataTask didReceiveData:data];
  237. }];
  238. }
  239. }
  240. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask willCacheResponse:(NSCachedURLResponse *)proposedResponse completionHandler:(void (^)(NSCachedURLResponse *cachedResponse))completionHandler
  241. {
  242. JAHPQNSURLSessionDemuxTaskInfo * taskInfo;
  243. taskInfo = [self taskInfoForTask:dataTask];
  244. if ([taskInfo.delegate respondsToSelector:@selector(URLSession:dataTask:willCacheResponse:completionHandler:)]) {
  245. [taskInfo performBlock:^{
  246. [taskInfo.delegate URLSession:session dataTask:dataTask willCacheResponse:proposedResponse completionHandler:completionHandler];
  247. }];
  248. } else {
  249. completionHandler(proposedResponse);
  250. }
  251. }
  252. @end