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

转载于:https://my.oschina.net/iq19900204/blog/821424

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值