1. 程式人生 > >GCD的簡單應用--非同步載入圖片

GCD的簡單應用--非同步載入圖片

在這裡,簡單介紹下GCD的應用。

1.程式設計場景 :

    在iPhone上做一個下載圖片的功能,很簡單,就是在螢幕上放置一個按鈕,點選該按鈕,顯示一個轉動的圓圈,表示正在下載,下載完成後,將圖片顯示出來。

2.主要程式碼如下:

#import "ViewController.h"

@interface ViewController ()

@property (nonatomic,strong) UIActivityIndicatorView *indicator;   // 指示檢視

@property (nonatomic,strong) UIImageView *imgV;                    // 顯示圖片

@property (nonatomic,strong) UIButton *btn;                        // 點選按鈕

@end

@implementation ViewController


- (void)viewDidLoad {

    [superviewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

    [self.viewaddSubview:self.btn];

}

-(UIActivityIndicatorView

*)indicator {

if (_indicator == nil) {

_indicator = [[UIActivityIndicatorViewalloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];

_indicator.frame = CGRectMake(0, 0, [UIScreenmainScreen].bounds.size.width, [UIScreenmainScreen].bounds.size.width);

_indicator.backgroundColor = [

UIColorlightGrayColor];

    }

    [self.viewaddSubview:_indicator];

return_indicator;

}

-(UIImageView *)imgV {

if (_imgV == nil) {

_imgV = [[UIImageViewalloc] initWithFrame:CGRectMake(0, 230, [UIScreenmainScreen].bounds.size.width, [UIScreenmainScreen].bounds.size.width)];

_imgV.backgroundColor = [UIColorblueColor];

    }

    [self.viewaddSubview:_imgV];

return_imgV;

}

-(UIButton *)btn {

if (_btn == nil) {

_btn = [UIButtonbuttonWithType:UIButtonTypeCustom];

_btn.frame = CGRectMake(10, 50, 200, 50);

_btn.backgroundColor = [UIColorredColor];

        [_btnsetTitle:@"點選載入圖片"forState:UIControlStateNormal];

        [_btnaddTarget:selfaction:@selector(loadImage) forControlEvents:UIControlEventTouchUpInside];

    }

return_btn;

}

/** 載入圖片 */

-(void)loadImage {

self.indicator.hidden = NO;

    [self.indicatorstartAnimating];

    [self.imgVaddSubview:self.indicator];

    // 開啟一個執行緒進行資料請求

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

NSURL *url1 = [NSURLURLWithString:@"http://pic.qiantucdn.com/58pic/18/32/08/32658PICPUs_1024.png"];

NSError *error;

NSData *data = [NSDatadataWithContentsOfURL:url1];

if (data != nil) {

            // 在主執行緒中完成UI操作

dispatch_async(dispatch_get_main_queue(), ^{

                [self.indicatorstopAnimating];

self.indicator.hidden = YES;

UIImage *image = [UIImageimageWithData:data];

self.imgV.image = image;

            });

        }else {

NSLog(@"error whin download:%@",error);

        }

    });

}

- (void)didReceiveMemoryWarning {

    [superdidReceiveMemoryWarning];

// Dispose of any resources that can be recreated.

}

@end