swift 同步 网络请求_IOS开发中异步网络请求上实现同步逻辑
IOS開發中異步網絡請求上實現同步邏輯
前提:
可能遇到一些問題,比如上傳多個數據,需要等多個數據上傳成功后做一定的處理,而且一個個上傳,萬一哪個上傳失敗了,后面就不需要上傳了,直接報錯。
之前ASI的網絡庫中是有同步請求的接口,所以很好處理,AFNetwork的網絡庫只有異步的網絡請求,該怎么實現呢?
1.循環異步拼組
- (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.信號量異步轉同步
__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
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的swift 同步 网络请求_IOS开发中异步网络请求上实现同步逻辑的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 华夏鼎茂债券c安全吗
- 下一篇: 当前元素_90行代码,15个元素实现无限