如何在iOS中asynchronous下载图像?
我想先创buildimageview到滚动view.there我设置的占位符图像或给imageview.so的背景颜色所有图像视图显示。
- (void)LoadDataInScrollView { dispatch_queue_t imageQueue = dispatch_queue_create("Image Queue",NULL); //totalImageGetDict into count total Number of object and generate imageview. for (int ivalue = 0; ivalue < [totalImageGetDict count]; ivalue++) { dispatch_async(imageQueue, ^{ //define x value CGFloat xOrigin =ivalue *ascrollView.frame.size.width+50; imageView = [[UIImageView alloc] init]; imageView.tag = ivalue; [imageView setBackgroundColor:[UIColor whiteColor]]; imageView.frame = CGRectMake(xOrigin-40,imgYpos, ascrollView.frame.size.width-20, scrollViewHight); //then here first i set already downloaded image.it's comes from another class. getImageLoadDict into images are already downloaded** if ([getImageLoadDict objectForKey:[NSNumber numberWithInteger:ivalue]]!= nil) { //dispatch_async(dispatch_get_main_queue(), ^{ [imageView setImage:[getImageLoadDict objectForKey:[NSNumber numberWithInteger:ivalue]]]; //}); } else { //totalImageGetDict into remaining images object and asynchronously download here. STVisionPhoto *photoObj = [totalImageGetDict objectForKey:[NSNumber numberWithInteger:ivalue]]; UIImage *newimage = [photoObj image]; dispatch_async(dispatch_get_main_queue(), ^{ [imageView setImage:newimage]; }); } [ascrollView addSubview:imageView]; }); } }
你可以使用SDWebImage来完成它,使用起来非常简单
编辑:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ UIImage * image = [UIImage imageWithData:[NSData dataWithContentsOfURL:your url]]; dispatch_async(dispatch_get_main_queue(), ^{ [imgview setImage:image]; }); });
如果你不想使用任何库,你可以试试这个
尝试使用此代码:
UIImageView *imgView = [[UIImageView alloc] init]; imgView.frame = CGRectMake(12.5, 12.5, 80, 80); dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ UIImage *profileImage; profileImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:YOUR_URL_STRING]]]; dispatch_async(dispatch_get_main_queue(), ^{ imgView.image = profileImage; }); }); [cell.contentView addSubview:imgView];
(void)loadImg:(NSString *)url img :(UIImageView *)imgView{ NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]]; __weak UIImageView *imageV = imgView; [imgView setImageWithURLRequest:request placeholderImage:[UIImage imageNamed:@"songRecDef"] success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) { imageV.image = image; [imageV setNeedsLayout]; NSLog(@"%@",response); } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) { [imageV setImage:[UIImage imageNamed:@"songRecDef"]]; NSLog(@"%@",error); }]; }