关于 ios 多图异步下载

来源:互联网 发布:华为云计算认证 编辑:程序博客网 时间:2024/05/16 19:47

通过dispatch_apply来下载,由于是同步线程所以只有当所有方法执行完之后,就是所有的图片下载完成之后,才会执行之后的代码,将此次执行来单独放到异步线程中区执行,从而达到图片统一下载,回到主线程中在刷新UI

NSMutableArray *array = [NSMutableArrayarrayWithCapacity:0];

    //记录图片数量,有空图时,移除不存在的图

    NSInteger sum =0;

    dispatch_queue_t queue =dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);

    dispatch_async(queue, ^{

        dispatch_apply(fileArray.count, queue, ^(size_t index) {

           UIImage *image = [selfimageWithURL:fileArray[index] andCompId:idarray[index]];

            if (image) {

                [array addObject:image];

            }else{

                //移除不存在的图

                sum += 1;

            }

        });

        if (array.count == fileArray.count - sum) {

            dispatch_async(dispatch_get_main_queue(), ^{

                if (array.count>0) {

                    NSArray *tempArray = [NSArrayarrayWithArray:self.dataArray];

                    [self.dataArray removeAllObjects];

                    [self.dataArrayaddObjectsFromArray:array];

                    [self.dataArrayaddObjectsFromArray:tempArray];

                }

                [self.collectionViewreloadData];

                [selfhideHud];

            });

        }

    });