首页 > 移动平台 > 详细

IOS UI多线程 NSThread 下载并显示图片到UIImageView

时间:2014-08-19 16:06:34      阅读:390      评论:0      收藏:0      [点我收藏+]

效果图

bubuko.com,布布扣

@property (weak,nonatomic)IBOutletUILabel *downLabelInfo;

@property (weak,nonatomic)IBOutletUIImageView *imageView;

 

@end

 

@implementationViewController

 

- (void)viewDidLoad

{

    [super viewDidLoad];

   

    NSString *url  =@"http://d.hiphotos.baidu.com/image/w%3D1366%3Bcrop%3D0%2C0%2C1366%2C768/sign=6cbcab9dabec8a13141a53e3c135aaec/aa64034f78f0f7369453c3730855b319ebc41316.jpg";

   

    @autoreleasepool {

        NSThread *thread = [[NSThreadalloc]initWithTarget:selfselector:@selector(downloadImage:)object:url];

        [thread start];

    }

 

}

 

- (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

 

}

 

-(void) downloadImage:(NSString *)url {

  

    // 要把显示的内容放到同步方法前面即可

    self->_downLabelInfo.text =@"正在下载图片中...";

   

    // 同步方法 会卡线程直到完成位置

   

    NSData *imageData = [NSDatadataWithContentsOfURL:[NSURLURLWithString:url]];

   

    UIImage *image =[UIImageimageWithData:imageData];

 

    if(image==nil)

    {

    }

    else

    {

        //self->_downLabelInfo.text = @"正在下载图片中...";所以这条语句写了也没用

        [self performSelectorOnMainThread:@selector(updateImageView:)withObject:(image)waitUntilDone:YES];

    }

}

 

-(void) updateImageView:(UIImage *)image

{

    self->_imageView.image = image;

 

    self->_imageView.frame=CGRectMake(self.view.frame.size.width/2-100,self.view.frame.size.height/2-100,200, 200);

    self->_downLabelInfo.textColor = [UIColorredColor];

    self->_downLabelInfo.text =@"图片下载完成";

}

@end

 

第二种方式使用 NSURLConnection  sendSynchronousRequest 同步方式获取图片内容并显示

将downloadImage方法修改如下

-(void) downloadImage:(NSString *)url

{

      self->_downLabelInfo.text =@"正在下载图片中...";

    NSURLRequest *request = [NSURLRequestrequestWithURL:[NSURLURLWithString:url]];

    NSError *error;

   // 此处将会造成阻塞

    NSData *data   = [NSURLConnectionsendSynchronousRequest:requestreturningResponse:nilerror:&error];

 

    if(data ==nil)

    {

        NSLog(@"nil");

 

    }

    else

    {

        UIImage *image =[UIImageimageWithData:data];

       

        self->_imageView.image = image;

        self->_downLabelInfo.textColor = [UIColorredColor];

        self->_downLabelInfo.text =@"图片下载完成";

 

    }

IOS UI多线程 NSThread 下载并显示图片到UIImageView,布布扣,bubuko.com

IOS UI多线程 NSThread 下载并显示图片到UIImageView

原文:http://www.cnblogs.com/llios/p/3922102.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!