swift 同步 网络请求_IOS开发中异步网络请求上实现同步逻辑
IOS開發(fā)中異步網(wǎng)絡請求上實現(xiàn)同步邏輯
前提:
可能遇到一些問題,比如上傳多個數(shù)據(jù),需要等多個數(shù)據(jù)上傳成功后做一定的處理,而且一個個上傳,萬一哪個上傳失敗了,后面就不需要上傳了,直接報錯。
之前ASI的網(wǎng)絡庫中是有同步請求的接口,所以很好處理,AFNetwork的網(wǎng)絡庫只有異步的網(wǎng)絡請求,該怎么實現(xiàn)呢?
1.循環(huán)異步拼組
- (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.信號量異步轉(zhuǎn)同步
__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實現(xiàn)上傳邏輯,完成發(fā)出通知或者block回調(diào)
2).用上傳數(shù)據(jù)創(chuàng)建Operation數(shù)組,加入NSOperationQueue中執(zhí)行
3).根據(jù)完成回調(diào)的結(jié)果和個數(shù)判斷結(jié)果,如果中間有失敗,可以關(guān)閉未執(zhí)行的Operation
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
《新程序員》:云原生和全面數(shù)字化實踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀總結(jié)
以上是生活随笔為你收集整理的swift 同步 网络请求_IOS开发中异步网络请求上实现同步逻辑的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 华夏鼎茂债券c安全吗
- 下一篇: 当前元素_90行代码,15个元素实现无限