IOS开发中异步网络请求上实现同步逻辑

2025-05-29 0 56

IOS开发中异步网络请求上实现同步逻辑

前提:

可能遇到一些问题,比如上传多个数据,需要等多个数据上传成功后做一定的处理,而且一个个上传,万一哪个上传失败了,后面就不需要上传了,直接报错。

之前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

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 IOS开发中异步网络请求上实现同步逻辑 https://www.kuaiidc.com/90592.html

相关文章

发表评论
暂无评论