CCDownloaderImpl-apple.mm 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722
  1. /****************************************************************************
  2. Copyright (c) 2015-2016 Chukong Technologies Inc.
  3. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
  4. http://www.cocos2d-x.org
  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. The above copyright notice and this permission notice shall be included in
  12. all copies or substantial portions of the Software.
  13. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. THE SOFTWARE.
  20. ****************************************************************************/
  21. #include "network/CCDownloaderImpl-apple.h"
  22. #include <queue>
  23. #import <Foundation/Foundation.h>
  24. #include "network/CCDownloader.h"
  25. #include "base/ccUTF8.h"
  26. ////////////////////////////////////////////////////////////////////////////////
  27. // OC Classes Declaration
  28. // this wrapper used to wrap C++ class DownloadTask into NSMutableDictionary
  29. @interface DownloadTaskWrapper : NSObject
  30. {
  31. std::shared_ptr<const cocos2d::network::DownloadTask> _task;
  32. NSMutableArray *_dataArray;
  33. }
  34. // temp vars for dataTask: didReceivedData callback
  35. @property (nonatomic) int64_t bytesReceived;
  36. @property (nonatomic) int64_t totalBytesReceived;
  37. -(id)init:(std::shared_ptr<const cocos2d::network::DownloadTask>&)t;
  38. -(cocos2d::network::DownloadTask *)get;
  39. -(void) addData:(NSData*) data;
  40. -(int64_t) transferDataToBuffer:(void*)buffer lengthOfBuffer:(int64_t)len;
  41. @end
  42. @interface DownloaderAppleImpl : NSObject <NSURLSessionDataDelegate, NSURLSessionDownloadDelegate>
  43. {
  44. const cocos2d::network::DownloaderApple *_outer;
  45. cocos2d::network::DownloaderHints _hints;
  46. std::queue<NSURLSessionTask*> _taskQueue;
  47. }
  48. @property (nonatomic, strong) NSURLSession *downloadSession;
  49. @property (nonatomic, strong) NSMutableDictionary *taskDict; // ocTask: DownloadTaskWrapper
  50. -(id)init:(const cocos2d::network::DownloaderApple *)o hints:(const cocos2d::network::DownloaderHints&) hints;
  51. -(const cocos2d::network::DownloaderHints&)getHints;
  52. -(NSURLSessionDataTask *)createDataTask:(std::shared_ptr<const cocos2d::network::DownloadTask>&) task;
  53. -(NSURLSessionDownloadTask *)createFileTask:(std::shared_ptr<const cocos2d::network::DownloadTask>&) task;
  54. -(void)abort:(NSURLSessionTask *)task;
  55. -(void)doDestroy;
  56. @end
  57. ////////////////////////////////////////////////////////////////////////////////
  58. // C++ Classes Implementation
  59. namespace cocos2d { namespace network {
  60. struct DownloadTaskApple : public IDownloadTask
  61. {
  62. DownloadTaskApple()
  63. : dataTask(nil)
  64. , downloadTask(nil)
  65. {
  66. DLLOG("Construct DownloadTaskApple %p", this);
  67. }
  68. virtual ~DownloadTaskApple()
  69. {
  70. DLLOG("Destruct DownloadTaskApple %p", this);
  71. }
  72. NSURLSessionDataTask *dataTask;
  73. NSURLSessionDownloadTask *downloadTask;
  74. };
  75. #define DeclareDownloaderImplVar DownloaderAppleImpl *impl = (__bridge DownloaderAppleImpl *)_impl
  76. // the _impl's type is id, we should convert it to subclass before call it's methods
  77. DownloaderApple::DownloaderApple(const DownloaderHints& hints)
  78. : _impl(nil)
  79. {
  80. DLLOG("Construct DownloaderApple %p", this);
  81. _impl = (__bridge void*)[[DownloaderAppleImpl alloc] init: this hints:hints];
  82. }
  83. DownloaderApple::~DownloaderApple()
  84. {
  85. DeclareDownloaderImplVar;
  86. [impl doDestroy];
  87. DLLOG("Destruct DownloaderApple %p", this);
  88. }
  89. IDownloadTask *DownloaderApple::createCoTask(std::shared_ptr<const DownloadTask>& task)
  90. {
  91. DownloadTaskApple* coTask = new (std::nothrow) DownloadTaskApple();
  92. DeclareDownloaderImplVar;
  93. if (task->storagePath.length())
  94. {
  95. coTask->downloadTask = [impl createFileTask:task];
  96. }
  97. else
  98. {
  99. coTask->dataTask = [impl createDataTask:task];
  100. }
  101. return coTask;
  102. }
  103. void DownloaderApple::abort(const std::unique_ptr<IDownloadTask> &task) {
  104. DLLOG("DownloaderApple:abort");
  105. DeclareDownloaderImplVar;
  106. cocos2d::network::DownloadTaskApple *downloadTask = (cocos2d::network::DownloadTaskApple *)task.get();
  107. NSURLSessionTask *taskOC = downloadTask->dataTask ? downloadTask->dataTask : downloadTask->downloadTask;
  108. [impl abort:taskOC];
  109. }
  110. }} // namespace cocos2d::network
  111. ////////////////////////////////////////////////////////////////////////////////
  112. // OC Classes Implementation
  113. @implementation DownloadTaskWrapper
  114. - (id)init: (std::shared_ptr<const cocos2d::network::DownloadTask>&)t
  115. {
  116. DLLOG("Construct DonloadTaskWrapper %p", self);
  117. _dataArray = [NSMutableArray arrayWithCapacity:8];
  118. [_dataArray retain];
  119. _task = t;
  120. return self;
  121. }
  122. -(const cocos2d::network::DownloadTask *)get
  123. {
  124. return _task.get();
  125. }
  126. -(void) addData:(NSData*) data
  127. {
  128. [_dataArray addObject:data];
  129. self.bytesReceived += data.length;
  130. self.totalBytesReceived += data.length;
  131. }
  132. -(int64_t) transferDataToBuffer:(void*)buffer lengthOfBuffer:(int64_t)len
  133. {
  134. int64_t bytesReceived = 0;
  135. int receivedDataObject = 0;
  136. __block char *p = (char *)buffer;
  137. for (NSData* data in _dataArray)
  138. {
  139. // check
  140. if (bytesReceived + data.length > len)
  141. {
  142. break;
  143. }
  144. // copy data
  145. [data enumerateByteRangesUsingBlock:^(const void *bytes,
  146. NSRange byteRange,
  147. BOOL *stop)
  148. {
  149. memcpy(p, bytes, byteRange.length);
  150. p += byteRange.length;
  151. *stop = NO;
  152. }];
  153. // accumulate
  154. bytesReceived += data.length;
  155. ++receivedDataObject;
  156. }
  157. // remove receivedNSDataObject from dataArray
  158. [_dataArray removeObjectsInRange:NSMakeRange(0, receivedDataObject)];
  159. self.bytesReceived -= bytesReceived;
  160. return bytesReceived;
  161. }
  162. -(void)dealloc
  163. {
  164. [_dataArray release];
  165. [super dealloc];
  166. DLLOG("Destruct DownloadTaskWrapper %p", self);
  167. }
  168. @end
  169. @implementation DownloaderAppleImpl
  170. - (id)init: (const cocos2d::network::DownloaderApple*)o hints:(const cocos2d::network::DownloaderHints&) hints
  171. {
  172. DLLOG("Construct DownloaderAppleImpl %p", self);
  173. // save outer task ref
  174. _outer = o;
  175. _hints = hints;
  176. // create task dictionary
  177. self.taskDict = [NSMutableDictionary dictionary];
  178. // create download session
  179. NSURLSessionConfiguration *defaultConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
  180. self.downloadSession = [NSURLSession sessionWithConfiguration:defaultConfig delegate:self delegateQueue:[NSOperationQueue mainQueue]];
  181. // self.downloadSession.sessionDescription = kCurrentSession;
  182. return self;
  183. }
  184. -(const cocos2d::network::DownloaderHints&)getHints
  185. {
  186. return _hints;
  187. }
  188. -(NSURLSessionDataTask *)createDataTask:(std::shared_ptr<const cocos2d::network::DownloadTask>&) task
  189. {
  190. const char *urlStr = task->requestURL.c_str();
  191. DLLOG("DownloaderAppleImpl createDataTask: %s", urlStr);
  192. NSURL *url = [NSURL URLWithString:[NSString stringWithUTF8String:urlStr]];
  193. NSURLRequest *request = nil;
  194. if (_hints.timeoutInSeconds > 0)
  195. {
  196. request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:(NSTimeInterval)_hints.timeoutInSeconds];
  197. }
  198. else
  199. {
  200. request = [NSURLRequest requestWithURL:url];
  201. }
  202. NSURLSessionDataTask *ocTask = [self.downloadSession dataTaskWithRequest:request];
  203. DownloadTaskWrapper* taskWrapper = [[DownloadTaskWrapper alloc] init:task];
  204. [self.taskDict setObject:taskWrapper forKey:ocTask];
  205. [taskWrapper release];
  206. if (_taskQueue.size() < _hints.countOfMaxProcessingTasks) {
  207. [ocTask resume];
  208. _taskQueue.push(nil);
  209. } else {
  210. _taskQueue.push(ocTask);
  211. }
  212. return ocTask;
  213. };
  214. -(NSURLSessionDownloadTask *)createFileTask:(std::shared_ptr<const cocos2d::network::DownloadTask>&) task
  215. {
  216. const char *urlStr = task->requestURL.c_str();
  217. DLLOG("DownloaderAppleImpl createFileTask: %s", urlStr);
  218. NSURL *url = [NSURL URLWithString:[NSString stringWithUTF8String:urlStr]];
  219. NSMutableURLRequest *request = nil;
  220. if (_hints.timeoutInSeconds > 0)
  221. {
  222. request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:(NSTimeInterval)_hints.timeoutInSeconds];
  223. }
  224. else
  225. {
  226. request = [NSMutableURLRequest requestWithURL:url];
  227. }
  228. for (auto it = task->header.begin(); it != task->header.end(); ++it) {
  229. NSString *keyStr = [NSString stringWithUTF8String:it->first.c_str()];
  230. NSString *valueStr = [NSString stringWithUTF8String:it->second.c_str()];
  231. [request setValue:valueStr forHTTPHeaderField:keyStr];
  232. }
  233. NSString *tempFilePath = [NSString stringWithFormat:@"%s%s", task->storagePath.c_str(), _hints.tempFileNameSuffix.c_str()];
  234. NSData *resumeData = [NSData dataWithContentsOfFile:tempFilePath];
  235. NSURLSessionDownloadTask *ocTask = nil;
  236. if (resumeData && task->header.size() <= 0)
  237. {
  238. ocTask = [self.downloadSession downloadTaskWithResumeData:resumeData];
  239. }
  240. else
  241. {
  242. ocTask = [self.downloadSession downloadTaskWithRequest:request];
  243. }
  244. DownloadTaskWrapper* taskWrapper = [[DownloadTaskWrapper alloc] init:task];
  245. [self.taskDict setObject:taskWrapper forKey:ocTask];
  246. [taskWrapper release];
  247. if (_taskQueue.size() < _hints.countOfMaxProcessingTasks) {
  248. [ocTask resume];
  249. _taskQueue.push(nil);
  250. } else {
  251. _taskQueue.push(ocTask);
  252. }
  253. return ocTask;
  254. };
  255. -(void)abort:(NSURLSessionTask *)task
  256. {
  257. // cancel all download task
  258. NSEnumerator * enumeratorKey = [self.taskDict keyEnumerator];
  259. for (NSURLSessionTask *taskKey in enumeratorKey)
  260. {
  261. if (task != taskKey) {
  262. continue;
  263. }
  264. DownloadTaskWrapper *wrapper = [self.taskDict objectForKey:taskKey];
  265. // no resume support for a data task
  266. std::string storagePath = [wrapper get]->storagePath;
  267. if(storagePath.length() == 0) {
  268. [taskKey cancel];
  269. }
  270. else {
  271. [(NSURLSessionDownloadTask *)taskKey cancelByProducingResumeData:^(NSData *resumeData) {
  272. if (resumeData)
  273. {
  274. NSString *tempFilePath = [NSString stringWithFormat:@"%s%s", storagePath.c_str(), _hints.tempFileNameSuffix.c_str()];
  275. NSString *tempFileDir = [tempFilePath stringByDeletingLastPathComponent];
  276. NSFileManager *fileManager = [NSFileManager defaultManager];
  277. BOOL isDir = false;
  278. if ([fileManager fileExistsAtPath:tempFileDir isDirectory:&isDir])
  279. {
  280. if (NO == isDir)
  281. {
  282. // REFINE: the directory is a file, not a directory, how to echo to developer?
  283. DLLOG("DownloaderAppleImpl temp dir is a file!");
  284. return;
  285. }
  286. }
  287. else
  288. {
  289. NSURL *tempFileURL = [NSURL fileURLWithPath:tempFileDir];
  290. if (NO == [fileManager createDirectoryAtURL:tempFileURL withIntermediateDirectories:YES attributes:nil error:nil])
  291. {
  292. // create directory failed
  293. DLLOG("DownloaderAppleImpl create temp dir failed");
  294. return;
  295. }
  296. }
  297. [resumeData writeToFile:tempFilePath atomically:YES];
  298. }
  299. }];
  300. }
  301. break;
  302. }
  303. }
  304. -(void)doDestroy
  305. {
  306. // cancel all download task
  307. NSEnumerator * enumeratorKey = [self.taskDict keyEnumerator];
  308. for (NSURLSessionDownloadTask *task in enumeratorKey)
  309. {
  310. DownloadTaskWrapper *wrapper = [self.taskDict objectForKey:task];
  311. // no resume support for a data task
  312. std::string storagePath = [wrapper get]->storagePath;
  313. if(storagePath.length() == 0) {
  314. [task cancel];
  315. }
  316. else {
  317. [task cancelByProducingResumeData:^(NSData *resumeData) {
  318. if (resumeData)
  319. {
  320. NSString *tempFilePath = [NSString stringWithFormat:@"%s%s", storagePath.c_str(), _hints.tempFileNameSuffix.c_str()];
  321. NSString *tempFileDir = [tempFilePath stringByDeletingLastPathComponent];
  322. NSFileManager *fileManager = [NSFileManager defaultManager];
  323. BOOL isDir = false;
  324. if ([fileManager fileExistsAtPath:tempFileDir isDirectory:&isDir])
  325. {
  326. if (NO == isDir)
  327. {
  328. // REFINE: the directory is a file, not a directory, how to echo to developer?
  329. DLLOG("DownloaderAppleImpl temp dir is a file!");
  330. return;
  331. }
  332. }
  333. else
  334. {
  335. NSURL *tempFileURL = [NSURL fileURLWithPath:tempFileDir];
  336. if (NO == [fileManager createDirectoryAtURL:tempFileURL withIntermediateDirectories:YES attributes:nil error:nil])
  337. {
  338. // create directory failed
  339. DLLOG("DownloaderAppleImpl create temp dir failed");
  340. return;
  341. }
  342. }
  343. [resumeData writeToFile:tempFilePath atomically:YES];
  344. }
  345. }];
  346. }
  347. }
  348. _outer = nullptr;
  349. while(!_taskQueue.empty())
  350. _taskQueue.pop();
  351. [self.downloadSession invalidateAndCancel];
  352. [self release];
  353. }
  354. -(void)dealloc
  355. {
  356. DLLOG("Destruct DownloaderAppleImpl %p", self);
  357. self.downloadSession = nil;
  358. self.taskDict = nil;
  359. [super dealloc];
  360. }
  361. #pragma mark - NSURLSessionTaskDelegate methods
  362. //@optional
  363. /* An HTTP request is attempting to perform a redirection to a different
  364. * URL. You must invoke the completion routine to allow the
  365. * redirection, allow the redirection with a modified request, or
  366. * pass nil to the completionHandler to cause the body of the redirection
  367. * response to be delivered as the payload of this request. The default
  368. * is to follow redirections.
  369. *
  370. * For tasks in background sessions, redirections will always be followed and this method will not be called.
  371. */
  372. //- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
  373. //willPerformHTTPRedirection:(NSHTTPURLResponse *)response
  374. // newRequest:(NSURLRequest *)request
  375. // completionHandler:(void (^)(NSURLRequest *))completionHandler;
  376. /* The task has received a request specific authentication challenge.
  377. * If this delegate is not implemented, the session specific authentication challenge
  378. * will *NOT* be called and the behavior will be the same as using the default handling
  379. * disposition.
  380. */
  381. //- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
  382. //didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
  383. // completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler;
  384. /* Sent if a task requires a new, unopened body stream. This may be
  385. * necessary when authentication has failed for any request that
  386. * involves a body stream.
  387. */
  388. //- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
  389. // needNewBodyStream:(void (^)(NSInputStream *bodyStream))completionHandler;
  390. /* Sent periodically to notify the delegate of upload progress. This
  391. * information is also available as properties of the task.
  392. */
  393. //- (void)URLSession:(NSURLSession *)session task :(NSURLSessionTask *)task
  394. // didSendBodyData:(int64_t)bytesSent
  395. // totalBytesSent:(int64_t)totalBytesSent
  396. // totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend;
  397. /* Sent as the last message related to a specific task. Error may be
  398. * nil, which implies that no error occurred and this task is complete.
  399. */
  400. - (void)URLSession:(NSURLSession *)session task :(NSURLSessionTask *)task
  401. didCompleteWithError:(NSError *)error
  402. {
  403. DLLOG("DownloaderAppleImpl task: \"%s\" didCompleteWithError: %d errDesc: %s"
  404. , [task.originalRequest.URL.absoluteString cStringUsingEncoding:NSUTF8StringEncoding]
  405. , (error ? (int)error.code: 0)
  406. , [error.localizedDescription cStringUsingEncoding:NSUTF8StringEncoding]);
  407. // clean wrapper C++ object
  408. DownloadTaskWrapper *wrapper = [self.taskDict objectForKey:task];
  409. if(_outer)
  410. {
  411. if(error)
  412. {
  413. int errorCode = (int)error.code;
  414. NSString *errorMsg = error.localizedDescription;
  415. if (error.code == NSURLErrorCancelled) {
  416. //cancel
  417. errorCode = cocos2d::network::DownloadTask::ERROR_ABORT;
  418. errorMsg = @"downloadFile:fail abort";
  419. }
  420. // fix Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"
  421. if (error.code == 2 && [wrapper get]->storagePath.length() > 0) {
  422. NSString *tempFilePath = [NSString stringWithFormat:@"%s%s", [wrapper get]->storagePath.c_str(), _hints.tempFileNameSuffix.c_str()];
  423. NSFileManager *fileManager = [NSFileManager defaultManager];
  424. [fileManager removeItemAtURL:[NSURL fileURLWithPath:tempFilePath] error:NULL];
  425. [wrapper get]->storagePath = "";
  426. }
  427. std::vector<unsigned char> buf; // just a placeholder
  428. _outer->onTaskFinish(*[wrapper get],
  429. cocos2d::network::DownloadTask::ERROR_IMPL_INTERNAL,
  430. errorCode,
  431. [errorMsg cStringUsingEncoding:NSUTF8StringEncoding],
  432. buf);
  433. }
  434. else if (![wrapper get]->storagePath.length())
  435. {
  436. // call onTaskFinish for a data task
  437. // (for a file download task, callback is called in didFinishDownloadingToURL)
  438. std::string errorString;
  439. const int64_t buflen = [wrapper totalBytesReceived];
  440. std::vector<unsigned char> data((size_t)buflen);
  441. char* buf = (char*)data.data();
  442. [wrapper transferDataToBuffer:buf lengthOfBuffer:buflen];
  443. _outer->onTaskFinish(*[wrapper get],
  444. cocos2d::network::DownloadTask::ERROR_NO_ERROR,
  445. 0,
  446. errorString,
  447. data);
  448. }
  449. else
  450. {
  451. NSInteger statusCode = ((NSHTTPURLResponse*)task.response).statusCode;
  452. // Check for error status code
  453. if (statusCode >= 400)
  454. {
  455. std::vector<unsigned char> buf; // just a placeholder
  456. const char *originalURL = [task.originalRequest.URL.absoluteString cStringUsingEncoding:NSUTF8StringEncoding];
  457. std::string errorMessage = cocos2d::StringUtils::format("Downloader: Failed to download %s with status code (%d)", originalURL, (int)statusCode);
  458. _outer->onTaskFinish(*[wrapper get],
  459. cocos2d::network::DownloadTask::ERROR_IMPL_INTERNAL,
  460. 0,
  461. errorMessage,
  462. buf);
  463. }
  464. }
  465. }
  466. [self.taskDict removeObjectForKey:task];
  467. while (!_taskQueue.empty() && _taskQueue.front() == nil) {
  468. _taskQueue.pop();
  469. }
  470. if (!_taskQueue.empty()) {
  471. [_taskQueue.front() resume];
  472. _taskQueue.pop();
  473. }
  474. }
  475. #pragma mark - NSURLSessionDataDelegate methods
  476. //@optional
  477. /* The task has received a response and no further messages will be
  478. * received until the completion block is called. The disposition
  479. * allows you to cancel a request or to turn a data task into a
  480. * download task. This delegate message is optional - if you do not
  481. * implement it, you can get the response as a property of the task.
  482. *
  483. * This method will not be called for background upload tasks (which cannot be converted to download tasks).
  484. */
  485. //- (void)URLSession:(NSURLSession *)session dataTask :(NSURLSessionDataTask *)dataTask
  486. // didReceiveResponse:(NSURLResponse *)response
  487. // completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler
  488. //{
  489. // DLLOG("DownloaderAppleImpl dataTask: response:%s", [response.description cStringUsingEncoding:NSUTF8StringEncoding]);
  490. // completionHandler(NSURLSessionResponseAllow);
  491. //}
  492. /* Notification that a data task has become a download task. No
  493. * future messages will be sent to the data task.
  494. */
  495. //- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
  496. //didBecomeDownloadTask:(NSURLSessionDownloadTask *)downloadTask;
  497. /* Sent when data is available for the delegate to consume. It is
  498. * assumed that the delegate will retain and not copy the data. As
  499. * the data may be discontiguous, you should use
  500. * [NSData enumerateByteRangesUsingBlock:] to access it.
  501. */
  502. - (void)URLSession:(NSURLSession *)session dataTask :(NSURLSessionDataTask *)dataTask
  503. didReceiveData:(NSData *)data
  504. {
  505. DLLOG("DownloaderAppleImpl dataTask: \"%s\" didReceiveDataLen %d",
  506. [dataTask.originalRequest.URL.absoluteString cStringUsingEncoding:NSUTF8StringEncoding],
  507. (int)data.length);
  508. if (nullptr == _outer)
  509. {
  510. return;
  511. }
  512. DownloadTaskWrapper *wrapper = [self.taskDict objectForKey:dataTask];
  513. [wrapper addData:data];
  514. std::function<int64_t(void *, int64_t)> transferDataToBuffer =
  515. [wrapper](void *buffer, int64_t bufLen)->int64_t
  516. {
  517. return [wrapper transferDataToBuffer:buffer lengthOfBuffer: bufLen];
  518. };
  519. _outer->onTaskProgress(*[wrapper get],
  520. wrapper.bytesReceived,
  521. wrapper.totalBytesReceived,
  522. dataTask.countOfBytesExpectedToReceive,
  523. transferDataToBuffer);
  524. }
  525. /* Invoke the completion routine with a valid NSCachedURLResponse to
  526. * allow the resulting data to be cached, or pass nil to prevent
  527. * caching. Note that there is no guarantee that caching will be
  528. * attempted for a given resource, and you should not rely on this
  529. * message to receive the resource data.
  530. */
  531. //- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
  532. // willCacheResponse:(NSCachedURLResponse *)proposedResponse
  533. // completionHandler:(void (^)(NSCachedURLResponse *cachedResponse))completionHandler;
  534. #pragma mark - NSURLSessionDownloadDelegate methods
  535. /* Sent when a download task that has completed a download. The delegate should
  536. * copy or move the file at the given location to a new location as it will be
  537. * removed when the delegate message returns. URLSession:task:didCompleteWithError: will
  538. * still be called.
  539. */
  540. - (void)URLSession:(NSURLSession *)session downloadTask :(NSURLSessionDownloadTask *)downloadTask
  541. didFinishDownloadingToURL:(NSURL *)location
  542. {
  543. DLLOG("DownloaderAppleImpl downloadTask: \"%s\" didFinishDownloadingToURL %s",
  544. [downloadTask.originalRequest.URL.absoluteString cStringUsingEncoding:NSUTF8StringEncoding],
  545. [location.absoluteString cStringUsingEncoding:NSUTF8StringEncoding]);
  546. if (nullptr == _outer)
  547. {
  548. return;
  549. }
  550. // On iOS 9 a response with status code 4xx(Client Error) or 5xx(Server Error)
  551. // might end up calling this delegate method, saving the error message to the storage path
  552. // and treating this download task as a successful one, so we need to check the status code here
  553. NSInteger statusCode = ((NSHTTPURLResponse*)downloadTask.response).statusCode;
  554. if (statusCode >= 400)
  555. {
  556. return;
  557. }
  558. DownloadTaskWrapper *wrapper = [self.taskDict objectForKey:downloadTask];
  559. const char * storagePath = [wrapper get]->storagePath.c_str();
  560. NSString *destPath = [NSString stringWithUTF8String:storagePath];
  561. NSFileManager *fileManager = [NSFileManager defaultManager];
  562. NSURL *destURL = nil;
  563. do
  564. {
  565. if ([destPath hasPrefix:@"file://"])
  566. {
  567. break;
  568. }
  569. if ('/' == [destPath characterAtIndex:0])
  570. {
  571. destURL = [NSURL fileURLWithPath:destPath];
  572. break;
  573. }
  574. // relative path, store to user domain default
  575. NSArray *URLs = [fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];
  576. NSURL *documentsDirectory = URLs[0];
  577. destURL = [documentsDirectory URLByAppendingPathComponent:destPath];
  578. } while (0);
  579. // Make sure we overwrite anything that's already there
  580. [fileManager removeItemAtURL:destURL error:NULL];
  581. // copy file to dest location
  582. int errorCode = cocos2d::network::DownloadTask::ERROR_NO_ERROR;
  583. int errorCodeInternal = 0;
  584. std::string errorString;
  585. NSError *error = nil;
  586. if ([fileManager copyItemAtURL:location toURL:destURL error:&error])
  587. {
  588. // success, remove temp file if it exist
  589. if (_hints.tempFileNameSuffix.length())
  590. {
  591. NSString *tempStr = [[destURL absoluteString] stringByAppendingFormat:@"%s", _hints.tempFileNameSuffix.c_str()];
  592. NSURL *tempDestUrl = [NSURL URLWithString:tempStr];
  593. [fileManager removeItemAtURL:tempDestUrl error:NULL];
  594. }
  595. }
  596. else
  597. {
  598. errorCode = cocos2d::network::DownloadTask::ERROR_FILE_OP_FAILED;
  599. if (error)
  600. {
  601. errorCodeInternal = (int)error.code;
  602. errorString = [error.localizedDescription cStringUsingEncoding:NSUTF8StringEncoding];
  603. }
  604. }
  605. std::vector<unsigned char> buf; // just a placeholder
  606. _outer->onTaskFinish(*[wrapper get], errorCode, errorCodeInternal, errorString, buf);
  607. }
  608. // @optional
  609. /* Sent periodically to notify the delegate of download progress. */
  610. - (void)URLSession:(NSURLSession *)session downloadTask :(NSURLSessionDownloadTask *)downloadTask
  611. didWriteData:(int64_t)bytesWritten
  612. totalBytesWritten:(int64_t)totalBytesWritten
  613. totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
  614. {
  615. // NSLog(@"DownloaderAppleImpl downloadTask: \"%@\" received: %lld total: %lld", downloadTask.originalRequest.URL, totalBytesWritten, totalBytesExpectedToWrite);
  616. if (nullptr == _outer)
  617. {
  618. return;
  619. }
  620. DownloadTaskWrapper *wrapper = [self.taskDict objectForKey:downloadTask];
  621. std::function<int64_t(void *, int64_t)> transferDataToBuffer; // just a placeholder
  622. _outer->onTaskProgress(*[wrapper get], bytesWritten, totalBytesWritten, totalBytesExpectedToWrite, transferDataToBuffer);
  623. }
  624. /* Sent when a download has been resumed. If a download failed with an
  625. * error, the -userInfo dictionary of the error will contain an
  626. * NSURLSessionDownloadTaskResumeData key, whose value is the resume
  627. * data.
  628. */
  629. - (void)URLSession:(NSURLSession *)session downloadTask :(NSURLSessionDownloadTask *)downloadTask
  630. didResumeAtOffset:(int64_t)fileOffset
  631. expectedTotalBytes:(int64_t)expectedTotalBytes
  632. {
  633. // NSLog(@"[REFINE]DownloaderAppleImpl downloadTask: \"%@\" didResumeAtOffset: %lld", downloadTask.originalRequest.URL, fileOffset);
  634. // 下载失败
  635. // self.downloadFail([self getDownloadRespose:XZDownloadFail identifier:self.identifier progress:0.00 downloadUrl:nil downloadSaveFileUrl:nil downloadData:nil downloadResult:@"下载失败"]);
  636. }
  637. @end