I'm using the following code
self.imageView = [[UIImageView alloc] init];
[self.imageView setImageWithURL:[NSURL URLWithString:url] placeholderImage:[UIImage imageNamed:#"profile-image-placeholder"]];
[self setNeedsLayout];
[self setNeedsDisplay];
but in drawRect can't see the image only the placeholder using the following
[self.imageView.image drawAtPoint:CGPointMake(15.0f, 5.0f)];
any ideas on this?
I think all you need to do is this. AFNetworking will cancel the image operation if the cell is reused so you don't need to worry about that edge case.
[self.imageView setImageWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]] placeholderImage:[UIImage imageNamed:#"profile-image-placeholder"] success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
self.imageview.image=image;
[self setNeedsLayout];
[self setNeedsDisplay];
} failure:nil];
Related
I have cobbled together some methods to resize images and put them into a UIScrollView for horizontal scrolling, however one of my problems is that I'm capturing strongly, and I have attempted a few options that I have read about, but all result in no images being displayed. I'm hoping one of you can help me resolve this issue so I can quit cooking so much memory when my app loads the images into the scroll view.
- (void)setImage:(NSURL *)imageURL errorImage:(UIImage *)errorImage{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:imageURL];
[request addValue:#"image/*" forHTTPHeaderField:#"Accept"];
UIImageView *newView = [[UIImageView alloc] initWithFrame: CGRectMake(self.x, 0, self.screenWidth, self.screenHight)];
[self.scrollView addSubview: newView];
self.x = (self.x + newView.frame.size.width);
if(self.x > self.view.frame.size.width) {
self.scrollView.contentSize = CGSizeMake(self.x, self.scrollView.frame.size.height);
}
[[newView subviews] makeObjectsPerformSelector:#selector(removeFromSuperview)]; // Remove previous that not stop
__block UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] init];
activityIndicator.frame = newView.bounds;
[activityIndicator setHidden:NO];
[activityIndicator startAnimating];
activityIndicator.color = [UIColor redColor];
[newView addSubview:activityIndicator];
void (^removeSpinner)(void) = ^{ // Desctuctor Block
if (activityIndicator) {
[activityIndicator setHidden:YES];
[activityIndicator stopAnimating];
[activityIndicator removeFromSuperview];
activityIndicator = nil;
}
};
[newView setImageWithURLRequest:request placeholderImage:nil success: ^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
removeSpinner();
// resize the resulting image for this device
newView.image = [self imageScaleCropToSize:image];
NSLog(#"successfully loaded image: %#", imageURL);
} failure: ^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
removeSpinner();
NSLog(#"failed loading [%#]: %#", imageURL, error);
}];
}
i want to use afnetworking method to download and show image into imageview.
another step is i want to save all image in case of user open application in offline mode.
there is a few article on SO that give method on how to use UrlCache and cache variable in url header.
with background of developing in android is there any way to make Afnetworking works like Imageloader
solution in android ? (saving file into program or document folder and retrive in offline mode)
this is my code for showing images in uicolleciotn view :
if (![appRecord.thumb_url isEqualToString:#""])
{
[myCell.imageView setImageWithURL:[NSURL URLWithString:appRecord.thumb_url] placeholderImage:[UIImage imageNamed:#"white.png"]];
__weak UIImageView *weakImageView = myCell.imageView;
NSURLRequest *request1 = [NSURLRequest requestWithURL:[NSURL URLWithString:appRecord.thumb_url]];
[myCell.imageView setImageWithURLRequest:request1
placeholderImage:[UIImage imageNamed:#"white.png"]
success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
UIImageView *strongImageView = weakImageView; // make local strong reference to protect against race conditions
if (!strongImageView) return;
[UIView transitionWithView:strongImageView
duration:0.3
options:UIViewAnimationOptionTransitionFlipFromRight
animations:^{
strongImageView.image = image;
}
completion:NULL];
}
failure:NULL];
}
after changing the code due to luvacu suggestion :
adding this to header :
#property (nonatomic, strong) NSURLRequest *strongRequest1;
and :
__block UIImageView *weakImageView = myCell.imageView;
NSURLRequest *request1 = [NSURLRequest requestWithURL:[NSURL URLWithString:appRecord.thumb_url]];
__block NSURLRequest *weakRequest1 = request1;
[myCell.imageView setImageWithURLRequest:request1
placeholderImage:[UIImage imageNamed:#"white.png"]
success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
UIImageView *strongImageView = weakImageView; // make local strong reference to protect against race conditions
if (!strongImageView) {
return;
}
[UIView transitionWithView:strongImageView
duration:0.3
options:UIViewAnimationOptionTransitionFlipFromRight
animations:^{
strongImageView.image = image;
}
completion:NULL];
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
NSURLRequest *strongRequest = weakRequest1;
UIImageView *strongImageView = weakImageView;
UIImage *cachedImage = [[UIImageView sharedImageCache] cachedImageForRequest:strongRequest];
if (cachedImage) {
[UIView transitionWithView:strongImageView
duration:0.3
options:UIViewAnimationOptionTransitionFlipFromRight
animations:^{
strongImageView.image = cachedImage;
}
completion:NULL];
}
}];
still no iamge apear after making program offline.
AFNetworking's category UIImageView+AFNetworking includes a NSCache for each image URL request. Try to load a cached image for that request, when the request fails.
__block UIImageView *weakImageView = myCell.imageView;
NSURLRequest *request1 = [NSURLRequest requestWithURL:[NSURL URLWithString:appRecord.thumb_url]];
__block NSURLRequest *weakRequest1 = request1;
[myCell.imageView setImageWithURLRequest:request1
placeholderImage:[UIImage imageNamed:#"white.png"]
success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
UIImageView *strongImageView = weakImageView; // make local strong reference to protect against race conditions
if (!strongImageView) {
return;
}
[UIView transitionWithView:strongImageView
duration:0.3
options:UIViewAnimationOptionTransitionFlipFromRight
animations:^{
strongImageView.image = image;
}
completion:NULL];
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
NSURLRequest *strongRequest = weakRequest1;
UIImage *cachedImage = [[UIImageView sharedImageCache] cachedImageForRequest:strongRequest]
if (cachedImage) {
[UIView transitionWithView:strongImageView
duration:0.3
options:UIViewAnimationOptionTransitionFlipFromRight
animations:^{
strongImageView.image = cachedImage;
}
completion:NULL];
}
}];
Also, you are loading the image twice. Remove the first one:
[myCell.imageView setImageWithURL:[NSURL URLWithString:appRecord.thumb_url] placeholderImage:[UIImage imageNamed:#"white.png"]];
I want to first create imageview onto the scroll view.there i set placeholder image or give Background color of imageview.so all image view are display.
- (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];
});
}
}
You can use SDWebImage to do it.It is pretty easy to use
Edit :
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];
});
});
You can try this if you don't want to use any library
Try to use this code:
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);
}];
}
I'm using a UICollectionView and want to display images fetched from a server in it's cells. To do this I'm using UIImageView+AFNetworking. In my cellForItemAtIndexPath method I have the following code:
__weak CustomCollectionViewCell *weakCell = cell;
[cell.cellImageView setImageWithURLRequest:request
placeholderImage:placeholderImage
success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
weakCell.cellImageView.image = image;
[weakCell setNeedsLayout];
} failure:nil];
The placeholder always show, but sometimes the downloaded images aren't showing. Any ideas on how I could solve this?
I suspect the problem is that you're on a background thread when you try to set the image, whereas you should always perform UI operations on the main thread.
Try setting the image in the main thread with something like
__weak CustomCollectionViewCell *weakCell = cell;
[cell.cellImageView setImageWithURLRequest:request
placeholderImage:placeholderImage
success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
dispatch_async(dispatch_get_main_queue(), ^{
weakCell.cellImageView.image = image;
});
} failure:nil];
I'm pretty sure that AFNetworking moves all the block execution on the main thread, I'm just wondering if you are sure that those images are correctly downloaded.
Try to log the image size of the retuned image, and if it is present always use a failure block, maybe just printing the error.
Something like that:
typeof(self) __weak weakCell = cell; //but you don't need in that scenario
[cell.cellImageView setImageWithURLRequest:request
placeholderImage:placeholderImage
success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
NSLog(#"Image %# scale %f", NSStringFromCGSize(image.size), image.scale);
weakCell.cellImageView.image = image;
[weakCell setNeedsLayout];
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
NSLog(#"Error %#",error.localizedDescription);
}];
Solution for you question
SDWebImage
You just need to #import <SDWebImage/UIImageView+WebCache.h> to your project, and you can define also the placeholder when image is being downloaded with just this code:
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
MyCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"MyCell"
forIndexPath:indexPath];
DLog(#"url at index %d : %#", indexPath.row, ((MyObject *)[self.list.array objectAtIndex:indexPath.row]).imageUrl);
MyObject *object = (MyObject *)[self.list.array objectAtIndex:indexPath.row];
[cell.imageView setImageWithURL:[NSURL URLWithString:#"http://www.domain.com/path/to/image.jpg"]
placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
return cell;
}
It also cache downloaded images and gives you great performance.
Hope it will help you!
After downloading the images, I replaced
[self.myCollectionView reloadData]
with
[self.myCollectionView reloadSections:[NSIndexSet indexSetWithIndex:0]];
then refresh and it works well, you can try it.
I am using table view to show a list of data. Each custom table cell has a back ground image coming from JSON. I use AFNetworking framework to download those image. But table view scrolling is not smooth. I create those cells using .xib file.
static NSString *CellIdentifire=#"CellId";
NSMutableDictionary *murDic=[matchListarry objectAtIndex:indexPath.row];
TTTCellFormatchList *matchListcell;
matchListcell=(TTTCellFormatchList *)[tableView dequeueReusableCellWithIdentifier:CellIdentifire];
if (matchListcell==nil)
{
NSArray *CellNib=[[NSBundle mainBundle] loadNibNamed:#"TTTCellFormatchListcontroller" owner:self options:nil];
matchListcell=(TTTCellFormatchList *)[CellNib objectAtIndex:0];
}
UIView *MainView=(UIView *)[matchListcell.contentView viewWithTag:101];
UIActivityIndicatorView *Spinner=(UIActivityIndicatorView *)[MainView viewWithTag:93];
//Clearing The back Ground
matchListcell.backgroundColor=[UIColor clearColor];
//Downlod back ground image in block and background thread
NSString *BackgroundImageStgring=[murDic valueForKey:#"MatchImage"];
UIImageView *BackgrounImage=(UIImageView *)[matchListcell.contentView viewWithTag:100];
NSURLRequest *request_img = [NSURLRequest requestWithURL:[NSURL URLWithString:BackgroundImageStgring]];
AFImageRequestOperation *operation = [AFImageRequestOperation imageRequestOperationWithRequest:request_img, imageProcessingBlock:nil, success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image)
{
if(image!=nil)
{
image=[image blurredImageWithRadius:2 iterations:1 tintColor:[UIColor darkGrayColor]];
[BackgrounImage setImage:image];
[Spinner stopAnimating];
[Spinner setHidden:YES];
}
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
[[UIImage imageNamed:#"picture.png"] applyLightEffect];
[BackgrounImage setImage:[UIImage imageNamed:#"picture.png"]];
NSLog(#"Error %#",error);
}];
[operation start];
// call background queue for dynamic loading of data
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
// load your dynamic data here
// call main queue here
dispatch_async(dispatch_get_main_queue(), ^{
// after loading data in background. use your downloaded data here.
});
});
Custom UITableView with UITextview is not scrolling smoothly in ios device