Преглед изворни кода

1.修改RA Image iOS上传错误重试调度。
2.修改RA Image iOS文件上传成功才能删除文件。

Pen Li пре 8 година
родитељ
комит
938f29b9f7

+ 1 - 0
common/upload/RAUploadManager.h

@@ -56,5 +56,6 @@ typedef NS_ENUM(NSInteger, QueueStatus) {
 //@property (nonatomic,weak) id <RAUploadManagerDelegate> delegate;
 
 - (BOOL)canUpload;
+- (void)addRetryOperation:(RAUploadOperation *)operation;
 
 @end

+ 110 - 11
common/upload/RAUploadManager.m

@@ -11,6 +11,13 @@
 #import "RAUtils.h"
 #import "UploadSettingController.h"
 
+@interface RAUploadManager ()
+
+@property (nonatomic,strong) NSTimer *retryTimer;
+@property (nonatomic,strong) NSMutableArray<RAUploadOperation *> *retryArr;
+
+@end
+
 @implementation RAUploadManager
 
 
@@ -118,9 +125,11 @@
 -(void) dealloc
 {
 
+    [self destructRetryTimer];
     [[NSNotificationCenter defaultCenter] removeObserver:self name:kReachabilityChangedNotification object:nil];
     [self.operation_queue removeObserver:self forKeyPath:@"operationCount"];
     [self.operation_queue removeObserver:self forKeyPath:@"arr_queue"];
+    
 }
 
 
@@ -130,7 +139,9 @@
     if([keyPath isEqualToString:@"operationCount"])
     {
 
-        if([[change objectForKey:NSKeyValueChangeNewKey] intValue]==0)
+//        [self checkRetryOperations];
+        
+        if(self.operation_queue.operationCount == 0 && self.retryArr.count == 0)
         {
             for(NSMutableDictionary* task in self.arr_queue)
             {
@@ -238,15 +249,17 @@
 -(void) removeTasks:(NSMutableArray*) tasks
 {
     
-    NSFileManager* fmanager = [NSFileManager new];
+    
     for(NSMutableDictionary* task in tasks)
     {
         
         [self stopTask:task];
-        NSError* error = nil;
-        bool bdel=[fmanager removeItemAtPath:[self filePath:task] error:&error];
-        if(!bdel)
-            DebugLog(@"file delete failed path:%@",[self filePath:task]);
+        // 文件上传成功才移除文件
+//        NSFileManager* fmanager = [NSFileManager new];
+//        NSError* error = nil;
+//        bool bdel=[fmanager removeItemAtPath:[self filePath:task] error:&error];
+//        if(!bdel)
+//            DebugLog(@"file delete failed path:%@",[self filePath:task]);
     }
     
     
@@ -285,13 +298,17 @@
 
 -(void) removeTask:(NSMutableDictionary*) task
 {
-    NSFileManager* fmanager = [NSFileManager new];
+    
     //    [self.arr_queue addObject:task];
+    
+    
     [self stopTask:task];
-    NSError* error = nil;
-    bool bdel=[fmanager removeItemAtPath:[self filePath:task] error:&error];
-    if(!bdel)
-        DebugLog(@"file delete failed path:%@",[self filePath:task]);
+    // 上传成功才删除文件
+//    NSFileManager* fmanager = [NSFileManager new];
+//    NSError* error = nil;
+//    bool bdel=[fmanager removeItemAtPath:[self filePath:task] error:&error];
+//    if(!bdel)
+//        DebugLog(@"file delete failed path:%@",[self filePath:task]);
     
 
 //    [self.arr_queue_lock lock];
@@ -461,4 +478,86 @@
     return YES;
 }
 
+#pragma mark - Retry
+
+- (NSMutableArray<RAUploadOperation *> *)retryArr {
+    if (!_retryArr) {
+        _retryArr = [NSMutableArray array];
+    }
+    return _retryArr;
+}
+
+- (void)addRetryOperation:(RAUploadOperation *)operation {
+    if (self.retryTimer == nil) {
+//        self.retryTimer = [NSTimer scheduledTimerWithTimeInterval:60 target:self selector:@selector(checkRetryOperations) userInfo:nil repeats:YES];
+        self.retryTimer = [NSTimer timerWithTimeInterval:60 target:self selector:@selector(checkRetryOperations) userInfo:nil repeats:YES];
+        [[NSRunLoop mainRunLoop] addTimer:self.retryTimer forMode:NSRunLoopCommonModes];
+    }
+    [self.retryArr addObject:operation];
+    
+    // 升序
+    [self.retryArr sortUsingComparator:^NSComparisonResult(RAUploadOperation* _Nonnull operation1, RAUploadOperation*  _Nonnull opertation2) {
+        
+        if (operation1.theRestOfWaitTimeInterval < opertation2.theRestOfWaitTimeInterval) {
+            return NSOrderedAscending;
+        } else {
+            return NSOrderedDescending;
+        }
+        
+    }];
+}
+
+- (void)checkRetryOperations {
+    
+    // 检查是否有需要重试的任务
+    if (self.retryArr.count == 0) {
+        return;
+    }
+    
+    NSMutableArray<RAUploadOperation *> *nextStartOperations = [NSMutableArray array];
+//    // 检查当前上传队列等待数量是否小于最大并发数
+//    if (self.operation_queue.operationCount < self.maxThread) {
+//
+////        // 根据最大并发数将剩余Operation全部添加进去
+////        NSInteger minCount = MIN(self.retryArr.count, self.maxThread - self.operation_queue.operationCount);
+//        for (int i = 0; i < self.retryArr.count; i++) {
+//            RAUploadOperation *operation = [self.retryArr objectAtIndex:i];
+//            operation.queuePriority = NSOperationQueuePriorityVeryHigh;
+//            [self.operation_queue addOperation:operation];
+//            [nextStartOperations addObject:operation];
+//        }
+//
+//    } else {
+        // 调度等待时间到达的Operation
+        __weak typeof(self) weakSelf = self;
+        
+        [self.retryArr enumerateObjectsUsingBlock:^(RAUploadOperation * _Nonnull operation, NSUInteger idx, BOOL * _Nonnull stop) {
+            
+            if (operation.theRestOfWaitTimeInterval <= 0) {
+                operation.queuePriority = NSOperationQueuePriorityVeryHigh;
+                [weakSelf.operation_queue addOperation:operation];
+                [nextStartOperations addObject:operation];
+            }
+            
+        }];
+//    }
+    
+    
+    
+    [self.retryArr removeObjectsInArray:nextStartOperations];
+    
+//    if (self.retryArr.count == 0) {
+//        [self destructRetryTimer];
+//    }
+    
+}
+
+- (void)destructRetryTimer {
+    if (self.retryTimer != nil) {
+        [self.retryTimer setFireDate:[NSDate distantFuture]];
+        [self.retryTimer invalidate];
+        self.retryTimer = nil;
+    }
+}
+
 @end

+ 3 - 0
common/upload/RAUploadOperation.h

@@ -18,4 +18,7 @@ typedef NS_ENUM(NSInteger, TaskStatus) {
 - (instancetype)initWithTaskinfo:(NSMutableDictionary*)taskinfo retry:(int) maxRetry;
 @property (nonatomic , copy) void (^updateUI)(void);
 //@property (nonatomic , copy) void (^operationFinish)(NSMutableDictionary* taskinfo);
+
+@property (nonatomic,assign,readonly) NSTimeInterval theRestOfWaitTimeInterval;///<剩余等待时间
+
 @end

+ 33 - 5
common/upload/RAUploadOperation.m

@@ -13,6 +13,9 @@
 #import "RAUtils.h"
 #import "const.h"
 
+
+static const NSTimeInterval waitTimeIntervalDelta = 60 * 3;
+
 @interface RAUploadOperation ()
 {
 //    NSString*   _threadName;
@@ -24,7 +27,11 @@
     NSURLSessionTask *_urlSessionTask;
 }
 
+@property (nonatomic,assign) NSTimeInterval joinTimeInterval;///<开始等待时间
+@property (nonatomic,assign) NSTimeInterval waitTimeInterval;///<需要等待的时间
+
 @end
+
 @implementation RAUploadOperation
 
 - (instancetype)initWithTaskinfo:(NSMutableDictionary*)taskinfo retry:(int) maxRetry
@@ -105,8 +112,14 @@
         if(r==2|| r==RESULT_BARCODE_ERROR)
         {
             block_task[@"status"]=[NSNumber numberWithInt:TaskStatusFinish];
-            if(r==2)
+            if(r==2) {
                 block_task[@"msg"]=@"upload successful";
+                // after V1.07 上传成功后移除文件
+                NSString *path = [weakself filePath:_taskinfo];
+                if (path != nil) {
+                    [RAUtils removeFileAtPath:path];
+                }
+            }
             else
                 block_task[@"msg"]=[@"warning: " stringByAppendingString:result[@"msg"]];
         }
@@ -138,7 +151,12 @@
                 operation.updateUI= weakself.updateUI;
                 operation.completionBlock = weakself.completionBlock;
                 block_task[@"operation"] = operation;
-                [Appdelegate.uploadManager.operation_queue addOperation:operation];
+//                [Appdelegate.uploadManager.operation_queue addOperation:operation];
+                
+                // retry:
+                operation.joinTimeInterval = [[NSDate date] timeIntervalSince1970];
+                operation.waitTimeInterval += waitTimeIntervalDelta;
+                [Appdelegate.uploadManager addRetryOperation:operation];
              //   [self upload:url];
             }
         }
@@ -189,10 +207,14 @@
 -(NSString*)filePath:(NSMutableDictionary*)task
 {
 
-    NSString *path = [RAUtils appCacheDirectory];
-    path= [path stringByAppendingPathComponent:task[@"path"]];
-    path= [path stringByAppendingPathComponent:task[@"file"]];
+//    NSString *path = [RAUtils appCacheDirectory];
+//    path= [path stringByAppendingPathComponent:task[@"path"]];
+//    path= [path stringByAppendingPathComponent:task[@"file"]];
     
+    // V1.07 之后图片不再保存到Temp
+    NSString *file = [task objectForKey:@"file"];
+    NSString *dir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
+    NSString *path = [dir stringByAppendingPathComponent:file];
     
     NSFileManager* fmanager = [NSFileManager new];
     
@@ -230,5 +252,11 @@
     [super cancel];
 }
 
+#pragma mark - Retry
+
+- (NSTimeInterval)theRestOfWaitTimeInterval {
+    NSTimeInterval currentTime = [[NSDate date] timeIntervalSince1970];
+    return  self.waitTimeInterval - (currentTime - self.joinTimeInterval);
+}
 
 @end