IOS多线程-线程间的通信

使用NSThread实现线程间的通信

#import "ViewController.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *imageView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)download {
    // 1.图片地址
    NSString *urlStr = @"http://image1.mop.com/images/project14/2012-10-19/13506138571471411.jpg";
    NSURL *imageUrl = [NSURL URLWithString:urlStr];
    
    // 2.根据图片的地址下载图片的二进制数据
    NSData *imageData = [NSData dataWithContentsOfURL:imageUrl];
    
    // 3.设置图片
    UIImage *image = [UIImage imageWithData:imageData];
    
    // 4.回到主线程,刷新UI界面
    [self.imageView performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:YES];
    
    NSLog(@"download --- %@", [NSThread currentThread]);
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self performSelectorInBackground:@selector(download) withObject:nil];
    
}

@end

实现效果

实现效果.png

⚠️注意!!!

如果点击屏幕发现不能正常下载图片,并且报以下错误的话

App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file.

说明你没有允许网络服务,还需要在info.plist文件中增加如下设置


打开网络服务.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,018评论 25 708
  • *面试心声:其实这些题本人都没怎么背,但是在上海 两周半 面了大约10家 收到差不多3个offer,总结起来就是把...
    Dove_iOS阅读 27,203评论 30 471
  • 鹦鹉说起在不知哪里听来的话 人们觉得很有道理 他们惊讶 赞赏它 鹦鹉不想重复那些话 它心中有自己的语言 有它的思想...
    行脚阿南阅读 308评论 0 5
  • 1. 在这堂课开始之前,如果你没有看过我的基础篇和进阶篇,建议先看看: 用一年时间从菜鸟变身斜杠青年,我是怎么做到...
    星潇月阅读 447评论 2 1
  • 阀门开启 眼睑关闭 我忘记了人类 只留下自己 小舟被波涛托起 重雾掩藏了山溪 花洒 喷出珍珠也有彩虹之雨 水汽融入...
    上林叶阅读 254评论 8 7