前提:
可能遇到一些問題,比如上傳多個數據,需要等多個數據上傳成功后做一定的處理,而且一個個上傳,萬一哪個上傳失敗了,后面就不需要上傳了,直接報錯。
之前ASI的網絡庫中是有同步請求的接口,所以很好處理,AFNetwork的網絡庫只有異步的網絡請求,該怎么實現呢?
1.循環異步拼組
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
- ( void )uploadFile:(NSArray *)imageArray atIndex:(NSInteger)index imagesCount:(NSInteger)count completeBlock:(uploadCompleteBlock)block { FNCircleImage *aTCImage = imageArray[index]; NSString *filepath = aTCImage.localFilePath; [self.resourceManager upload:filepath progress:nil completion:^(NSString * _Nullable urlString, NSError * _Nullable error) { if (error == nil) { aTCImage.remoteUrl = urlString; NSInteger idx = index + 1; if (idx >= count) { block(nil); } else { [self uploadFile:imageArray atIndex:idx imagesCount:count completeBlock:block]; } } else { block(error); } }]; } |
2.信號量異步轉同步
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
__block NSError *e = nil; [imageArray enumerateObjectsUsingBlock:^(NSString *filePath, NSUInteger idx, BOOL * _Nonnull stop) { __block dispatch_semaphore_t t = dispatch_semaphore_create(0); [self upload:filepath progress:nil completion:^(NSString * _Nullable urlString, NSError * _Nullable error) { if (error == nil) { } else { e = error; *stop = YES; } dispatch_semaphore_signal(t); }]; dispatch_semaphore_wait(t, DISPATCH_TIME_FOREVER); }]; |
3.NSOperationQueue可控隊列
1).繼承NSOperation實現上傳邏輯,完成發出通知或者block回調
2).用上傳數據創建Operation數組,加入NSOperationQueue中執行
3).根據完成回調的結果和個數判斷結果,如果中間有失敗,可以關閉未執行的Operation
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!