多线程网络下载图片

it2026-05-25  13

小Demo展示

#import "ViewController.h"@interface ViewController ()@property (nonatomic, strong) UIImageView *myImage;@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    self.view.backgroundColor = [UIColor cyanColor];       self.myImage = [[UIImageView alloc] initWithFrame:self.view.bounds];       [self.view addSubview:self.myImage];            }//当手指触摸屏幕的时候,从网络下载一张图片到控制器的view上显示- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{          //1.获取一个全局窜行队列    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);    //2.把任务添加到队列中执行    dispatch_async(queue, ^{                     NSLog(@"%@",[NSThread currentThread]);//打印的结果;{number = 2, name = (null)}         //3.从网络上下载图片        NSURL *url = [NSURL URLWithString:@"https://img14.360buyimg.com/n7/jfs/t277/193/1005339798/768456/29136988/542d0798N19d42ce3.jpg"];               NSData *data = [NSData dataWithContentsOfURL:url];               UIImage *image = [UIImage imageWithData:data];               NSLog(@"图片加载完成");                   //4.回到主线程,展示图片        dispatch_async(dispatch_get_main_queue(), ^{                       self.myImage.image = image;                       NSLog(@"当前线程:---%@",[NSThread currentThread]);//{number = 1, name = main}                   });           });    }

转载于:https://www.cnblogs.com/ryc--520/articles/5037150.html

相关资源:下载网络图片 (整合多线程、内存缓存、本地文件缓存~)
最新回复(0)