#import "ViewController.h"
/*
如果下载地址不是https 则将以下步骤进行,允许xcode下载任意路径的文件。
1.在Info.plist中添加NSAppTransportSecurity类型Dictionary。
2.在NSAppTransportSecurity下添加NSAllowsArbitraryLoads类型Boolean,值设为YES
*/
@interface ViewController ()
@property (nonatomic,strong)UIButton * downBtn;
@property (nonatomic,strong)UIImageView * imageView;
@end
@implementation ViewController
- (UIButton *)downBtn{
if (!_downBtn) {
_downBtn = [UIButton buttonWithType:UIButtonTypeSystem];
_downBtn.frame =CGRectMake(110, 350, 100, 40);
[_downBtn setTitle:@"下载图片" forState:UIControlStateNormal];
[_downBtn addTarget:self action:@selector(download) forControlEvents:UIControlEventTouchUpInside];
}
return _downBtn;
}
- (UIImageView *)imageView{
if (!_imageView) {
_imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 320, 300)];
_imageView.contentMode = UIViewContentModeScaleAspectFit;
}
return _imageView;
}
-(void)download{
NSString * imagePath = @"http://pic64.nipic.com/file/20150418/20717244_162150469000_2.jpg";
NSURL * imageURL = [NSURL URLWithString:imagePath];
//把网络数据下载到NSData中,是耗时操作,时间由网速决定
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
//0 是默认优先级的值 default级别
dispatch_async(queue, ^{
NSData *data = [NSData dataWithContentsOfURL:imageURL];
UIImage *image = [UIImage imageWithData:data];
//把图片放入到图片控件中,因为图片控件的更新必须在主线程中执行,所以我们需要主队列异步
dispatch_async(dispatch_get_main_queue(), ^{
self.imageView.image =image;
});
});
}
- (void)viewDidLoad {
[super viewDidLoad];
[self.view addSubview:self.imageView];
[self.view addSubview:self.downBtn];
}
@end