异步线程加载

91 阅读1分钟
#import "ViewController.h"

@interface ViewController ()

@property (nonatomic,strong) UIImageView *imageView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.view addSubview:self.imageView];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    //GCD中的队列:串行(2)|并发(2)
    //01 创建队列
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    //02 封装下载图片的任务,并且添加到队列
    //同步函数|异步函数
    dispatch_async(queue, ^{
        //03 URL
        NSURL *url = [NSURL URLWithString:@"http://article.fd.zol-img.com.cn/t_s500x2000/g4/M08/04/06/Cg-4WlPoSQaIJMNHAAFQxnn-qSoAAQZGQCqggkAAVDe827.jpg"];
        //04 下载图片的二进制数据到本地
        NSData *imageData= [NSData dataWithContentsOfURL:url];
        //05 转换格式
        UIImage *image = [UIImage imageWithData:imageData];
        NSLog(@"Download-----%@",[NSThread currentThread]);
        //回到主线程设置图片 主队列 + 同步函数|异步函数
        dispatch_sync(dispatch_get_main_queue(), ^{
            //设置图片
            self.imageView.image = image;
            NSLog(@"UI-----%@",[NSThread currentThread]);
        });
    });
}

- (UIImageView *)imageView {
    if (!_imageView) {
        _imageView = [[UIImageView alloc] init];
        _imageView.backgroundColor = [[UIColor redColor] colorWithAlphaComponent:0.1];
        _imageView.frame = CGRectMake(100, 100, 200, 200);
    }
    return _imageView;
}

@end