RAUploadOperation.m 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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. NSLog(@"---------------start--------------------");
  59. AppDelegate* Appdelegate=(AppDelegate*)[UIApplication sharedApplication].delegate;
  60. // sleep(3);
  61. //
  62. // [self willChangeValueForKey:@"isFinished"];
  63. // finished = true;
  64. // [self didChangeValueForKey:@"isFinished"];
  65. //
  66. //
  67. // return;
  68. __weak typeof(self) weakself = self;
  69. __block NSMutableDictionary* block_task = _taskinfo;
  70. [_taskinfo removeObjectForKey:@"msg"]; // 重试开始消息仍然存在,需要清除
  71. // NSString *md5 = [RAUtils md5WithFile:[self filePath:_taskinfo ]];
  72. DebugLog(@"task %@",_taskinfo);
  73. NSString* file_path = [self filePath:_taskinfo];
  74. BOOL noFileTag = [[_taskinfo objectForKey:@"noFile"] boolValue]; // Apex Drivers 2018.6.6
  75. if(file_path==nil && !noFileTag)
  76. {
  77. DebugLog(@"error no file");
  78. block_task[@"status"]=[NSNumber numberWithInt:TaskStatusError];
  79. block_task[@"progress"]=[NSNumber numberWithDouble:0.0];
  80. [self willChangeValueForKey:@"isFinished"];
  81. finished = true;
  82. [self didChangeValueForKey:@"isFinished"];
  83. return;
  84. }
  85. _urlSessionTask = [NetworkUtils upload:[self filePath:_taskinfo ] Params:_taskinfo[@"params"] ToHost:_taskinfo[@"url"] Result:^(NSMutableDictionary *result) {
  86. blockDebugLog(@"upload result: %@",result);
  87. int r=[result[@"result"] intValue];
  88. if(r==2|| r==RESULT_BARCODE_ERROR)
  89. {
  90. block_task[@"status"]=[NSNumber numberWithInt:TaskStatusFinish];
  91. if(r==2) {
  92. block_task[@"msg"]=@"upload successful";
  93. // after V1.07 上传成功后移除文件
  94. NSString *path = [weakself filePath:_taskinfo];
  95. if (path != nil) {
  96. [RAUtils removeFileAtPath:path];
  97. }
  98. }
  99. else
  100. block_task[@"msg"]=[@"warning: " stringByAppendingString:result[@"msg"]];
  101. }
  102. else
  103. {
  104. BOOL canUpload = [Appdelegate.uploadManager canUpload];
  105. BOOL isReachable = [Appdelegate.uploadManager reachable];
  106. DebugLog(@"can upload %@",@(canUpload));
  107. if (!canUpload) {
  108. block_task[@"status"]=[NSNumber numberWithInt:TaskStatusStop];
  109. block_task[@"progress"]=[NSNumber numberWithDouble:0.0];
  110. block_task[@"msg"]= @"Can only use wifi to upload";
  111. }
  112. else if (weakself.isCancelled || !isReachable) {
  113. block_task[@"status"] = [NSNumber numberWithInt:TaskStatusStop] ;
  114. block_task[@"progress"] = [NSNumber numberWithDouble:0.0];
  115. block_task[@"msg"]= @"";
  116. }
  117. else if([block_task[@"retry"] intValue]>=_maxRetry)
  118. {
  119. block_task[@"status"]=[NSNumber numberWithInt:TaskStatusError];
  120. block_task[@"progress"]=[NSNumber numberWithDouble:0.0];
  121. block_task[@"msg"]=result[@"msg"];
  122. }
  123. else
  124. {
  125. block_task[@"retry"]=[NSNumber numberWithInt:[block_task[@"retry"] intValue]+1];
  126. block_task[@"status"]=[NSNumber numberWithInt:TaskStatusWait];
  127. block_task[@"progress"]=[NSNumber numberWithDouble:0.0];
  128. block_task[@"msg"]= @"connection lost, retry...";
  129. RAUploadOperation* operation = [[RAUploadOperation alloc] initWithTaskinfo:block_task retry:_maxRetry];
  130. operation.updateUI= weakself.updateUI;
  131. operation.completionBlock = weakself.completionBlock;
  132. block_task[@"operation"] = operation;
  133. // [Appdelegate.uploadManager.operation_queue addOperation:operation];
  134. // retry:
  135. operation.joinTimeInterval = [[NSDate date] timeIntervalSince1970];
  136. operation.waitTimeInterval = weakself.waitTimeInterval + Appdelegate.uploadManager.retryTimeInterval;
  137. [Appdelegate.uploadManager addRetryOperation:operation];
  138. // [self upload:url];
  139. }
  140. }
  141. dispatch_async(dispatch_get_main_queue(), ^{
  142. if(weakself.updateUI)
  143. weakself.updateUI();
  144. });
  145. [weakself willChangeValueForKey:@"isFinished"];
  146. finished = true;
  147. [weakself didChangeValueForKey:@"isFinished"];
  148. // [self completeOperation];
  149. } Progress:^(NSURLSessionTask *task,double progress) {
  150. BOOL 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)completeOperation {
  193. //// [self willChangeValueForKey:@"isFinished"];
  194. //// [self willChangeValueForKey:@"isExecuting"];
  195. ////
  196. //// executing = NO;
  197. //// finished = YES;
  198. ////
  199. //// [self didChangeValueForKey:@"isExecuting"];
  200. //// [self didChangeValueForKey:@"isFinished"];
  201. //}
  202. - (void)dealloc
  203. {
  204. // dumpThreads(@"dealloc");
  205. DebugLog(@"operation Dealloc %@",self);
  206. }
  207. - (void)cancel {
  208. DebugLog(@"operation Cancel %@",self);
  209. if (_urlSessionTask.state == NSURLSessionTaskStateRunning || _urlSessionTask.state == NSURLSessionTaskStateSuspended) {
  210. DebugLog(@"cancel session task");
  211. [_urlSessionTask suspend];
  212. [_urlSessionTask cancel];
  213. }
  214. [super cancel];
  215. }
  216. #pragma mark - Retry
  217. - (NSTimeInterval)theRestOfWaitTimeInterval {
  218. NSTimeInterval currentTime = [[NSDate date] timeIntervalSince1970];
  219. return self.waitTimeInterval - (currentTime - self.joinTimeInterval);
  220. }
  221. @end