RAUploadOperation.m 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. //
  2. // RAUploadOperation.m
  3. // test_autolayout
  4. //
  5. // Created by Ray on 03/05/2017.
  6. // Copyright © 2017 USAI. All rights reserved.
  7. //
  8. #import "RAUploadOperation.h"
  9. #import "NetworkUtils.h"
  10. #import <UIKit/UIKit.h>
  11. #import "AppDelegate.h"
  12. #import "RAUtils.h"
  13. #import "const.h"
  14. //static const NSTimeInterval waitTimeIntervalDelta = 60 * 3;
  15. @interface RAUploadOperation ()
  16. {
  17. // NSString* _threadName;
  18. // NSString* _url;
  19. BOOL executing;
  20. BOOL finished;
  21. NSMutableDictionary* _taskinfo;
  22. int _maxRetry;
  23. NSURLSessionTask *_urlSessionTask;
  24. }
  25. @property (nonatomic,assign) NSTimeInterval joinTimeInterval;///<开始等待时间
  26. @property (nonatomic,assign) NSTimeInterval waitTimeInterval;///<需要等待的时间
  27. @end
  28. @implementation RAUploadOperation
  29. - (instancetype)initWithTaskinfo:(NSMutableDictionary*)taskinfo retry:(int) maxRetry
  30. {
  31. self = [super init];
  32. if (self) {
  33. // if (name!=nil)
  34. // _threadName = name;
  35. _maxRetry = maxRetry;
  36. // executing = NO;
  37. // finished = NO;
  38. _taskinfo=taskinfo;
  39. }
  40. return self;
  41. }
  42. - (BOOL)isConcurrent {
  43. return YES;
  44. }
  45. //
  46. - (BOOL)isExecuting {
  47. return executing;
  48. }
  49. - (BOOL)isFinished {
  50. return finished;
  51. }
  52. - (void)start
  53. {
  54. [self willChangeValueForKey:@"isExecuting"];
  55. executing = true;
  56. _taskinfo[@"status"]=[NSNumber numberWithInt:TaskStatusStart];
  57. [self didChangeValueForKey:@"isExecuting"];
  58. DebugLog(@"---------------start--------------------");
  59. // AppDelegate* Appdelegate=(AppDelegate*)[UIApplication sharedApplication].delegate;
  60. __weak typeof(self) weakself = self;
  61. __block NSMutableDictionary* block_task = _taskinfo;
  62. [_taskinfo removeObjectForKey:@"msg"]; // 重试开始消息仍然存在,需要清除
  63. // NSString *md5 = [RAUtils md5WithFile:[self filePath:_taskinfo ]];
  64. DebugLog(@"task %@",_taskinfo);
  65. NSString* file_path = [self filePath:_taskinfo];
  66. BOOL noFileTag = [[_taskinfo objectForKey:@"noFile"] boolValue]; // Apex Drivers 2018.6.6
  67. if(file_path==nil && !noFileTag)
  68. {
  69. DebugLog(@"error no file");
  70. block_task[@"status"]=[NSNumber numberWithInt:TaskStatusError];
  71. block_task[@"progress"]=[NSNumber numberWithDouble:0.0];
  72. [self willChangeValueForKey:@"isFinished"];
  73. finished = true;
  74. [self didChangeValueForKey:@"isFinished"];
  75. return;
  76. }
  77. _urlSessionTask = [NetworkUtils upload:[self filePath:_taskinfo ] Params:_taskinfo[@"params"] ToHost:_taskinfo[@"url"] Result:^(NSMutableDictionary *result) {
  78. blockDebugLog(@"upload result: %@",result);
  79. int r=[result[@"result"] intValue];
  80. if(r==2|| r==RESULT_BARCODE_ERROR)
  81. {
  82. block_task[@"status"]=[NSNumber numberWithInt:TaskStatusFinish];
  83. if(r==2) {
  84. block_task[@"msg"]=@"upload successful";
  85. // after V1.07 上传成功后移除文件
  86. NSString *path = [weakself filePath:self->_taskinfo];
  87. if (path != nil) {
  88. [RAUtils removeFileAtPath:path];
  89. }
  90. }
  91. else
  92. block_task[@"msg"]=[@"warning: " stringByAppendingString:result[@"msg"]];
  93. }
  94. else
  95. {
  96. AppDelegate* Appdelegate=(AppDelegate*)[UIApplication sharedApplication].delegate;
  97. BOOL canUpload = [Appdelegate.uploadManager canUpload];
  98. BOOL isReachable = [Appdelegate.uploadManager reachable];
  99. DebugLog(@"can upload %@",@(canUpload));
  100. if (!canUpload) {
  101. block_task[@"status"]=[NSNumber numberWithInt:TaskStatusStop];
  102. block_task[@"progress"]=[NSNumber numberWithDouble:0.0];
  103. block_task[@"msg"]= @"Can only use wifi to upload";
  104. }
  105. else if (weakself.isCancelled || !isReachable) {
  106. block_task[@"status"] = [NSNumber numberWithInt:TaskStatusStop] ;
  107. block_task[@"progress"] = [NSNumber numberWithDouble:0.0];
  108. block_task[@"msg"]= @"";
  109. }
  110. else if([block_task[@"retry"] intValue]>=self->_maxRetry)
  111. {
  112. block_task[@"status"]=[NSNumber numberWithInt:TaskStatusError];
  113. block_task[@"progress"]=[NSNumber numberWithDouble:0.0];
  114. block_task[@"msg"]=result[@"msg"];
  115. }
  116. else
  117. {
  118. block_task[@"retry"]=[NSNumber numberWithInt:[block_task[@"retry"] intValue]+1];
  119. block_task[@"status"]=[NSNumber numberWithInt:TaskStatusWait];
  120. block_task[@"progress"]=[NSNumber numberWithDouble:0.0];
  121. block_task[@"msg"]= @"connection lost, retry...";
  122. RAUploadOperation* operation = [[RAUploadOperation alloc] initWithTaskinfo:block_task retry:self->_maxRetry];
  123. operation.updateUI= weakself.updateUI;
  124. operation.completionBlock = weakself.completionBlock;
  125. block_task[@"operation"] = operation;
  126. // [Appdelegate.uploadManager.operation_queue addOperation:operation];
  127. // retry:
  128. operation.joinTimeInterval = [[NSDate date] timeIntervalSince1970];
  129. operation.waitTimeInterval = weakself.waitTimeInterval + Appdelegate.uploadManager.retryTimeInterval;
  130. [Appdelegate.uploadManager addRetryOperation:operation];
  131. // [self upload:url];
  132. }
  133. }
  134. dispatch_async(dispatch_get_main_queue(), ^{
  135. if(weakself.updateUI)
  136. weakself.updateUI();
  137. });
  138. [weakself willChangeValueForKey:@"isFinished"];
  139. self->finished = true;
  140. [weakself didChangeValueForKey:@"isFinished"];
  141. // [self completeOperation];
  142. } Progress:^(NSURLSessionTask *task,double progress) {
  143. // NSDictionary *param = [[NSUserDefaults standardUserDefaults] objectForKey:kUploadSetting];
  144. // BOOL onlyWiFi = false;
  145. // if (param) {
  146. // BOOL onlyWiFi = [[param objectForKey:@"only_wifi"] boolValue];
  147. //
  148. // }
  149. // AppDelegate* Appdelegate=(AppDelegate*)[UIApplication sharedApplication].delegate;
  150. BOOL canUpload = [[RAUploadManager sharedManager] canUpload];//[Appdelegate.uploadManager canUpload];
  151. if (!canUpload) {
  152. printf("cancel task on progress");
  153. [task cancel];
  154. return ;
  155. }
  156. dispatch_async(dispatch_get_main_queue(), ^{
  157. // ((UIProgressView*) block_task[@"ui_pregress"]).progress = progress;
  158. block_task[@"progress"]=[NSNumber numberWithFloat:progress];
  159. // NSLog(@"updateUI progress %p",weakself);
  160. DebugLog(@"update UI %@ p:%f",weakself.updateUI,progress);
  161. if(weakself.updateUI)
  162. {
  163. // NSLog(@"updateUI progress CALL");
  164. weakself.updateUI();
  165. }
  166. });
  167. } DecryptHandler:^id(NSString *result) {
  168. return @"bibibi";
  169. }];
  170. //完成下载
  171. // DebugLog(@"operation finish %@",self);
  172. // [self didChangeValueForKey:@"isExecuting"];
  173. }
  174. -(NSString*)filePath:(NSMutableDictionary*)task
  175. {
  176. // NSString *path = [RAUtils appCacheDirectory];
  177. // path= [path stringByAppendingPathComponent:task[@"path"]];
  178. // path= [path stringByAppendingPathComponent:task[@"file"]];
  179. // V1.07 之后图片不再保存到Temp
  180. NSString *file = [task objectForKey:@"file"];
  181. if (file.length == 0) { // Apex Drivers 2018.6.6
  182. return nil;
  183. }
  184. NSString *dir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
  185. NSString *path = [dir stringByAppendingPathComponent:file];
  186. NSFileManager* fmanager = [NSFileManager new];
  187. bool file_exist=[fmanager fileExistsAtPath:path];
  188. if(!file_exist)
  189. return nil;
  190. return path;
  191. }
  192. - (void)dealloc
  193. {
  194. // dumpThreads(@"dealloc");
  195. DebugLog(@"operation Dealloc %@",self);
  196. }
  197. - (void)cancel {
  198. DebugLog(@"operation Cancel %@",self);
  199. if (_urlSessionTask.state == NSURLSessionTaskStateRunning || _urlSessionTask.state == NSURLSessionTaskStateSuspended) {
  200. DebugLog(@"cancel session task");
  201. [_urlSessionTask suspend];
  202. [_urlSessionTask cancel];
  203. }
  204. [super cancel];
  205. }
  206. #pragma mark - Retry
  207. - (NSTimeInterval)theRestOfWaitTimeInterval {
  208. NSTimeInterval currentTime = [[NSDate date] timeIntervalSince1970];
  209. return self.waitTimeInterval - (currentTime - self.joinTimeInterval);
  210. }
  211. @end