I'm writing app for iPhone using SDK 4.0 that needs to download, re-size and show many images one by one.
I tried to do that with a simple ASIHTTPRequest
, but these operations turned out to be very expensive. So I created subclass that inherits from ASIHTTPRequest
and I'm trying to override requestFinished
. I have though a problem with that. Well.. I need to somehow set that image on my UIImageView
. I don't really have any idea how to do that properly.
I tried to create UIImage
property in my subclass and put my re-sized image there and then just take it from request. Alas, it causes problems. I'm getting EXC_BAD_ACCESS. I guess that method might be dangerous due to concurrency. Is there any easy and safe way to do that? I thought about parsing that image to NSData
and somehow switch it with requests response.
EDIT: JosephH: I did what you wrote there. It helped for small pictures - I mean this which don't need to be resized. So when I added resizing - it lagged again. Here is some code:
#import "BackgroundHTTPRequest.h"
@implementation BackgroundHTTPRequest
@synthesize myimg;
-(UIImage *)imageWithImage:(UIImage*)imagee scaledToSize:(CGSize)newSize
{
// Create a bitmap context.
UIGraphicsBeginImageContextWithOptions(newSize, YES, [UIScreen mainScreen].scale);
[imagee drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
- (void)requestFinished{
NSData *responseData = [self responseData];
UIImage *tempimg = [UIImage imageWithData:responseData];
CGFloat ratio = tempimg.size.height / tempimg.size.width;
CGFloat widthmax = 320;
CGFloat heightmax = widthmax * ratio;
myimg = [self imageWithImage:tempimg scaledToSize:CGSizeMake(widthmax, heightmax)];
[super requestFinished];
}
- (void)dealloc{
self.myimg = nil;
[super dealloc];
}
@end
And some code where it happens:
- (IBAction)grabURLInBackground:(NSURL *)url
{
[self.myrequest setDelegate:nil];
[self.myrequest cancel];
[self.myrequest release];
self.myrequest = [[BackgroundHTTPRequest requestWithURL:url] retain];
[myrequest setDelegate:self];
[myrequest startAsynchronous];
}
- (void)requestFinished:(BackgroundHTTPRequest *)request
{
// Use when fetching binary data
if ((NSNull *)self == [NSNull null]){
[request clearDelegatesAndCancel];
} else {
if (self.image)
self.image.image = myrequest.myimg;
}
self.myrequest = nil;
}
Plus adding line
[self.myrequest setCacheStoragePolicy:ASICachePermanentlyCacheStoragePolicy];
Didn't help.