info 文件设置网络请求状态为YES
@interface ViewController ()
{
UITextField *tf;
UIButton *btn;
UIImageView *imgView;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//btn
btn=[UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame=CGRectMake(240, 100, 140, 30);
[btn setTitle:@"获取并显示图片" forState:UIControlStateNormal];
[btn addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
//imgView
imgView=[[UIImageView alloc]initWithFrame:CGRectMake(50, 150, 300, 300)];
[self.view addSubview:imgView];
}
-(void)click:(id)sender{
// sudo apachectl start
NSString *urlStr=@"http://f8.topitme.com/8/5b/d7/11252902191b2d75b8o.jpg";
NSThread *threadA=[[NSThread alloc]initWithTarget:self selector:@selector(downLoadImg:) object:urlStr];
[threadA start];
}
// 下载图片的方法
-(void)downLoadImg:(NSString*)url{
NSURL *uuu = [NSURL URLWithString:url];
NSData *data = [NSData dataWithContentsOfURL:uuu];
NSLog(@"data=%ld",data.length);
UIImage *img=[UIImage imageWithData:data];
// 调用主线程 执行更新图片的功能
if (img!=nil) {
[self performSelectorOnMainThread:@selector(updateImg:) withObject:img waitUntilDone:YES];
}else{
[[[UIAlertView alloc]initWithTitle:@"提示" message:@"图片下载失败" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil]show];
}
}
// 更新图片的方法
-(void)updateImg:(UIImage*)img{
imgView.image=img;
}
网友评论