当前位置:编程学习 > wap >>

iOS-下载一张网络图片

效果图:
 
源代码连接:点击打开链接
 
(1) 在ViewController.h里面关联一个imageview和一个button
 
@property (weak, nonatomic) IBOutletUIImageView *showImageView;
- (IBAction)loadImage:(id)sender;
 
 
 
(2)在ViewController.m里面
 
第一种方法:
- (IBAction)loadImage:(id)sender {
   
    NSURL *url = [NSURLURLWithString:@"http://pica.nipic.com/2007-12-12/20071212235955316_2.jpg"];
 
    dispatch_queue_t queue =dispatch_queue_create("loadImage",NULL);
   dispatch_async(queue, ^{
        
       NSData *resultData = [NSDatadataWithContentsOfURL:url];
       UIImage *img = [UIImageimageWithData:resultData];
        
        dispatch_sync(dispatch_get_main_queue(), ^{
           self.showImageView.image = img;
        });
        
    });
 
}
 
第二种方法:
- (IBAction)loadImage:(id)sender {
    
    NSURL *url = [NSURLURLWithString:@"http://pica.nipic.com/2007-12-12/20071212235955316_2.jpg"];
 
   NSData *resultData = [NSDatadataWithContentsOfURL:url];
   UIImage *img = [UIImageimageWithData:resultData];
   self.showImageView.image = img;
      
}
 
第三种方法(异步下载:):
ViewController.h
@property(nonatomic,retain)NSMutableData *mutableData;
@property (weak, nonatomic) IBOutletUIImageView *showImageView;
- (IBAction)loadImage:(id)sender;
 
ViewController.m
- (IBAction)loadImage:(id)sender {
    
    NSURL *url = [NSURLURLWithString:@"http://pica.nipic.com/2007-12-12/20071212235955316_2.jpg"];
    NSMutableURLRequest *request = [[NSMutableURLRequestalloc] init];
    [requestsetURL:url];
    [requestsetHTTPMethod:@"GET"]; //设置请求方式
    [request setTimeoutInterval:60];//设置超时时间
   self.mutableData = [[NSMutableDataalloc] init];
    [NSURLConnectionconnectionWithRequest:request delegate:self];//发送一个异步请求
       
}
 
#pragma mark - NSURLConnection delegate
//数据加载过程中调用,获取数据
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [self.mutableDataappendData:data];
}
 
//数据加载完成后调用
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
   UIImage *image = [UIImageimageWithData:self.mutableData];
   self.showImageView.image = image;
}
 
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
   NSLog(@"请求网络失败:%@",error);
}
 
补充:移动开发 , IOS ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,