CCDownloader-apple.mm 24 KB

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