iOS下载一张网络图片 -电脑资料

电脑资料 时间:2019-01-01 我要投稿
【www.unjs.com - 电脑资料】

    效果图:

   

    源代码连接:点击打开链接

    (1) 在ViewController.h里面关联一个imageview和一个button

    @property (weak, nonatomic) IBOutletUIImageView *showImageView;

    - (IBAction)loadImage:(id)sender;

    (2)在ViewController.m里面

    第一种方法:

    - (IBAction)loadImage:(id)sender {

    NSURL *url = [NSURLURLWithString:@"//pic..nipic.com/2007-12-12/20071212235955316_2.jpg?x-oss-process=style/qr.unjs"];

    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:@"//pic..nipic.com/2007-12-12/20071212235955316_2.jpg?x-oss-process=style/qr.unjs"];

    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:@"//pic..nipic.com/2007-12-12/20071212235955316_2.jpg?x-oss-process=style/qr.unjs"];

    NSMutableURLRequest *request = [[NSMutableURLRequestalloc] init];

    [requestsetURL:url];

    [requestsetHTTPMethod:@"GET"]; //设置请求方式

    [request setTimeoutInterval:60];//设置超时时间

    self.mutableData = [[NSMutableDataalloc] init];

    [NSURLConnectionconnectionWithRequest:request delegate:self];//发送一个异步请求

    }

    #pragma mark - NSURLConnection delegate

    //数据加载过程中调用,获取数据dnzg.cn\

    - (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);

    }

最新文章