IOS 异步下载图片

来源:互联网 发布:八爪鱼采集器mac版 编辑:程序博客网 时间:2024/04/28 23:43
//下载图片

    //创建url

   //方式1

    NSURL *imageUrl = [NSURL URLWithString:PicURL];
    /*
     NSData *data = [[NSData alloc]initWithContentsOfURL:imageUrl];
     NSLog(@"%@",data);
     UIImage *image = [[UIImage alloc]initWithData:data];
     imageview.image = image;
     */
   
    //方式2使用NSURLsession 请求图片
     NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession] dataTaskWithURL:imageUrl completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
     if (error || !data) {
     return ;
     }
     UIImage *image = [[UIImage alloc]initWithData:data];
     imageview.image = image;
     }];
     //执行网络请求
     [dataTask resume];
     */
   
     //方式3 使用NSURLConnection请求图片
     //创建NSURLRequest
     NSURLRequest *request = [NSURLRequest requestWithURL:imageUrl];
     //使用异步请求
     [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
     if (connectionError || !data) {
     return ;
     }
     UIImage *image = [[UIImage alloc]initWithData:data];
     imageview.image = image;
     }];
   
0 0
原创粉丝点击