使用线程下载网络图片

使用线程下载网络图片_第1张图片
屏幕快照 2016-09-29 14.44.38.png

点击按钮,使用线程下载网络图片

@property (strong, nonatomic) IBOutlet UIImageView *iv;
@property (strong, nonatomic) IBOutlet UIButton *btn;
- (IBAction)showImage:(id)sender;

- (IBAction)showImage:(id)sender {
    
    NSString *url = @"http://ppt.downhot.com/d/file/p/2014/07/24/e8660d99f4cf021d4f0fc80b11902779.jpg";
    NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(downloadImageFormURL:) object:url];
    [thread start];
}

//定义一个方法作为线程的执行体
-(void)downloadImageFormURL:(NSString *)url{
    //从网络获取数据
    NSData *data = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:url]];
    
    UIImage *image = [[UIImage alloc] initWithData:data];
    if (image != nil) {
        //在主线程中执行updateUI:的方法
        [self performSelectorOnMainThread:@selector(updateUI:) withObject:image waitUntilDone:YES];
    }
    else{
        NSLog(@"----下载图片出现错误----");
    }
}

-(void)updateUI:(UIImage *)image{
    self.iv.image = image;
}

你可能感兴趣的:(使用线程下载网络图片)