// // RAUploadOperation.m // test_autolayout // // Created by Ray on 03/05/2017. // Copyright © 2017 USAI. All rights reserved. // #import "RAUploadOperation.h" #import "NetworkUtils.h" #import #import "AppDelegate.h" #import "RAUtils.h" #import "const.h" //static const NSTimeInterval waitTimeIntervalDelta = 60 * 3; @interface RAUploadOperation () { // NSString* _threadName; // NSString* _url; BOOL executing; BOOL finished; NSMutableDictionary* _taskinfo; int _maxRetry; NSURLSessionTask *_urlSessionTask; } @property (nonatomic,assign) NSTimeInterval joinTimeInterval;///<开始等待时间 @property (nonatomic,assign) NSTimeInterval waitTimeInterval;///<需要等待的时间 @end @implementation RAUploadOperation - (instancetype)initWithTaskinfo:(NSMutableDictionary*)taskinfo retry:(int) maxRetry { self = [super init]; if (self) { // if (name!=nil) // _threadName = name; _maxRetry = maxRetry; // executing = NO; // finished = NO; _taskinfo=taskinfo; } return self; } - (BOOL)isConcurrent { return YES; } // - (BOOL)isExecuting { return executing; } - (BOOL)isFinished { return finished; } - (void)start { [self willChangeValueForKey:@"isExecuting"]; executing = true; _taskinfo[@"status"]=[NSNumber numberWithInt:TaskStatusStart]; [self didChangeValueForKey:@"isExecuting"]; DebugLog(@"---------------start--------------------"); // AppDelegate* Appdelegate=(AppDelegate*)[UIApplication sharedApplication].delegate; __weak typeof(self) weakself = self; __block NSMutableDictionary* block_task = _taskinfo; [_taskinfo removeObjectForKey:@"msg"]; // 重试开始消息仍然存在,需要清除 // NSString *md5 = [RAUtils md5WithFile:[self filePath:_taskinfo ]]; DebugLog(@"task %@",_taskinfo); NSString* file_path = [self filePath:_taskinfo]; BOOL noFileTag = [[_taskinfo objectForKey:@"noFile"] boolValue]; // Apex Drivers 2018.6.6 if(file_path==nil && !noFileTag) { DebugLog(@"error no file"); block_task[@"status"]=[NSNumber numberWithInt:TaskStatusError]; block_task[@"progress"]=[NSNumber numberWithDouble:0.0]; [self willChangeValueForKey:@"isFinished"]; finished = true; [self didChangeValueForKey:@"isFinished"]; return; } _urlSessionTask = [NetworkUtils upload:[self filePath:_taskinfo ] Params:_taskinfo[@"params"] ToHost:_taskinfo[@"url"] Result:^(NSMutableDictionary *result) { blockDebugLog(@"upload result: %@",result); int r=[result[@"result"] intValue]; if(r==2|| r==RESULT_BARCODE_ERROR) { block_task[@"status"]=[NSNumber numberWithInt:TaskStatusFinish]; if(r==2) { block_task[@"msg"]=@"upload successful"; // after V1.07 上传成功后移除文件 NSString *path = [weakself filePath:self->_taskinfo]; if (path != nil) { [RAUtils removeFileAtPath:path]; } } else block_task[@"msg"]=[@"warning: " stringByAppendingString:result[@"msg"]]; } else { AppDelegate* Appdelegate=(AppDelegate*)[UIApplication sharedApplication].delegate; BOOL canUpload = [Appdelegate.uploadManager canUpload]; BOOL isReachable = [Appdelegate.uploadManager reachable]; DebugLog(@"can upload %@",@(canUpload)); if (!canUpload) { block_task[@"status"]=[NSNumber numberWithInt:TaskStatusStop]; block_task[@"progress"]=[NSNumber numberWithDouble:0.0]; block_task[@"msg"]= @"Can only use wifi to upload"; } else if (weakself.isCancelled || !isReachable) { block_task[@"status"] = [NSNumber numberWithInt:TaskStatusStop] ; block_task[@"progress"] = [NSNumber numberWithDouble:0.0]; block_task[@"msg"]= @""; } else if([block_task[@"retry"] intValue]>=self->_maxRetry) { block_task[@"status"]=[NSNumber numberWithInt:TaskStatusError]; block_task[@"progress"]=[NSNumber numberWithDouble:0.0]; block_task[@"msg"]=result[@"msg"]; } else { block_task[@"retry"]=[NSNumber numberWithInt:[block_task[@"retry"] intValue]+1]; block_task[@"status"]=[NSNumber numberWithInt:TaskStatusWait]; block_task[@"progress"]=[NSNumber numberWithDouble:0.0]; block_task[@"msg"]= @"connection lost, retry..."; RAUploadOperation* operation = [[RAUploadOperation alloc] initWithTaskinfo:block_task retry:self->_maxRetry]; operation.updateUI= weakself.updateUI; operation.completionBlock = weakself.completionBlock; block_task[@"operation"] = operation; // [Appdelegate.uploadManager.operation_queue addOperation:operation]; // retry: operation.joinTimeInterval = [[NSDate date] timeIntervalSince1970]; operation.waitTimeInterval = weakself.waitTimeInterval + Appdelegate.uploadManager.retryTimeInterval; [Appdelegate.uploadManager addRetryOperation:operation]; // [self upload:url]; } } dispatch_async(dispatch_get_main_queue(), ^{ if(weakself.updateUI) weakself.updateUI(); }); [weakself willChangeValueForKey:@"isFinished"]; self->finished = true; [weakself didChangeValueForKey:@"isFinished"]; // [self completeOperation]; } Progress:^(NSURLSessionTask *task,double progress) { // NSDictionary *param = [[NSUserDefaults standardUserDefaults] objectForKey:kUploadSetting]; // BOOL onlyWiFi = false; // if (param) { // BOOL onlyWiFi = [[param objectForKey:@"only_wifi"] boolValue]; // // } // AppDelegate* Appdelegate=(AppDelegate*)[UIApplication sharedApplication].delegate; BOOL canUpload = [[RAUploadManager sharedManager] canUpload];//[Appdelegate.uploadManager canUpload]; if (!canUpload) { printf("cancel task on progress"); [task cancel]; return ; } dispatch_async(dispatch_get_main_queue(), ^{ // ((UIProgressView*) block_task[@"ui_pregress"]).progress = progress; block_task[@"progress"]=[NSNumber numberWithFloat:progress]; // NSLog(@"updateUI progress %p",weakself); DebugLog(@"update UI %@ p:%f",weakself.updateUI,progress); if(weakself.updateUI) { // NSLog(@"updateUI progress CALL"); weakself.updateUI(); } }); } DecryptHandler:^id(NSString *result) { return @"bibibi"; }]; //完成下载 // DebugLog(@"operation finish %@",self); // [self didChangeValueForKey:@"isExecuting"]; } -(NSString*)filePath:(NSMutableDictionary*)task { // NSString *path = [RAUtils appCacheDirectory]; // path= [path stringByAppendingPathComponent:task[@"path"]]; // path= [path stringByAppendingPathComponent:task[@"file"]]; // V1.07 之后图片不再保存到Temp NSString *file = [task objectForKey:@"file"]; if (file.length == 0) { // Apex Drivers 2018.6.6 return nil; } NSString *dir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]; NSString *path = [dir stringByAppendingPathComponent:file]; NSFileManager* fmanager = [NSFileManager new]; bool file_exist=[fmanager fileExistsAtPath:path]; if(!file_exist) return nil; return path; } - (void)dealloc { // dumpThreads(@"dealloc"); DebugLog(@"operation Dealloc %@",self); } - (void)cancel { DebugLog(@"operation Cancel %@",self); if (_urlSessionTask.state == NSURLSessionTaskStateRunning || _urlSessionTask.state == NSURLSessionTaskStateSuspended) { DebugLog(@"cancel session task"); [_urlSessionTask suspend]; [_urlSessionTask cancel]; } [super cancel]; } #pragma mark - Retry - (NSTimeInterval)theRestOfWaitTimeInterval { NSTimeInterval currentTime = [[NSDate date] timeIntervalSince1970]; return self.waitTimeInterval - (currentTime - self.joinTimeInterval); } @end