IOS UI多線程 NSThread 下載並顯示圖片到UIImageView

來源:互聯網
上載者:User

標籤:blog   http   color   使用   os   io   strong   for   

@property (weak,nonatomic)IBOutletUILabel *downLabelInfo;

@property (weak,nonatomic)IBOutletUIImageView *imageView;

 

@end

 

@implementationViewController

 

- (void)viewDidLoad

{

    [super viewDidLoad];

   

    NSString *url  [email protected]"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 [email protected]"正在下載圖片中...";

   

    // 同步方法 會卡線程直到完成位置

   

    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 [email protected]"圖片下載完成";

}

@end

 

第二種方式使用 NSURLConnection  sendSynchronousRequest 同步方式擷取圖片內容並顯示

將downloadImage方法修改如下

-(void) downloadImage:(NSString *)url

{

      self->_downLabelInfo.text [email protected]"正在下載圖片中...";

    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 [email protected]"圖片下載完成";

 

    }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.