CCDownloader-apple.mm 25 KB

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