iOS开发-学习记录

swift监测所有异步线程全部完成

2018-09-14  本文已影响0人  Guomingjian
//
//  ViewController.swift
//  GCD_001
//
//  Created by 郭明健 on 2018/9/14.
//  Copyright © 2018年 GuoMingJian. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //监测异步任务全部完成后执行其他任务:
        
        let imageUrl1 = NSURL.init(string: "https://store.storeimages.cdn-apple.com/8755/as-images.apple.com/is/image/AppleInc/aos/published/images/m/bp/mbp13/space/mbp13-space-select-201807_GEO_CN?wid=1808&hei=1680&fmt=jpeg&qlt=80&.v=1534460284487")
        
        let imageUrl2 = NSURL.init(string: "https://store.storeimages.cdn-apple.com/8755/as-images.apple.com/is/image/AppleInc/aos/published/images/m/ac/macbook/air/macbook-air-select-201706_GEO_CN?wid=904&hei=840&fmt=jpeg&qlt=80&op_usm=0.5,0.5&.v=1505774695525")
        
        let imageUrl3 = NSURL.init(string: "https://gss3.bdstatic.com/-Po3dSag_xI4khGkpoWK1HF6hhy/baike/w%3D790/sign=13979c4896cad1c8d0bbfe2e4f3f67c4/5366d0160924ab18b4f26d5036fae6cd7a890bf4.jpg")
        
        let group = DispatchGroup.init();
        
        group.enter()
        MJTool.init().downloadImage(imageUrl1! as URL) { (image, error, finished) in
            print("图片下载1:\(String(describing: image))");
            group.leave()
        };
        
        group.enter()
        MJTool.init().downloadImage(imageUrl2! as URL) { (image, error, finished) in
            print("图片下载2:\(String(describing: image))");
            group.leave()
        };
        
        group.enter()
        MJTool.init().downloadImage(imageUrl3! as URL) { (image, error, finished) in
            print("图片下载3:\(String(describing: image))");
            group.leave()
        };
        
        group.notify(queue: DispatchQueue.main) {
            print("所有图片全部下载完成!")
        }
        
    }
    
}

MJTool.m

//
//  MJTool.m
//  GCD_001
//
//  Created by 郭明健 on 2018/9/14.
//  Copyright © 2018年 GuoMingJian. All rights reserved.
//

#import "MJTool.h"
#import <SDWebImage/SDWebImageDownloader.h>

@implementation MJTool

- (void)downloadImage:(NSURL *)imageUrl
            completed:(void(^)(UIImage *image, NSError *error, BOOL finished))completed
{
    SDWebImageDownloader *loader = [SDWebImageDownloader sharedDownloader];
    loader.downloadTimeout = 5;
    [loader downloadImageWithURL:imageUrl options:SDWebImageDownloaderAllowInvalidSSLCertificates progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
    } completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished) {
        completed(image, error, finished);
    }];
}

@end

上一篇下一篇

猜你喜欢

热点阅读