您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 多執行緒:用 NSThread 下載並顯示圖片到 UIImageView

編輯:iOS 開發綜合

效果圖:

@property (weak, nonatomic) IBOutlet UILabel *downLabelInfo;
@property (weak, nonatomic) IBOutlet UIImageView *imageView;

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

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

    @autoreleasepool {
        NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(downloadImage:) object:url];
        [thread start];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)downloadImage:(NSString *)url
{
    // 把要顯示的內容放到同步方法前面
    self->_downLabelInfo.text = @"正在下載圖片中...";

    // 同步方法會卡住線程直到完成
    NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
    UIImage *image = [UIImage imageWithData:imageData];

    if (image == nil)
    {
    }
    else
    {
        [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 = [UIColor redColor];
    self->_downLabelInfo.text = @"圖片下載完成";
}

@end

第二種方式:使用 NSURLConnection sendSynchronousRequest 取得圖片內容並顯示

將 downloadImage 方法修改如下:

-(void)downloadImage:(NSString *)url
{
    self->_downLabelInfo.text = @"正在下載圖片中...";

    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    NSError *error;

    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];

    if (data == nil)
    {
        NSLog(@"nil");
    }
    else
    {
        UIImage *image = [UIImage imageWithData:data];
        self->_imageView.image = image;
        self->_downLabelInfo.textColor = [UIColor redColor];
        self->_downLabelInfo.text = @"圖片下載完成";
    }
}
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved