I’ve created a category for UIImageView to allow for async loading of images:
@implementation UIImageView (ImageLoader)
- (void) asyncLoadImageIntoView:(NSURL *)imageURL withLoadingIndicator:(BOOL)isLoadingIndicator {
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:imageURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];
(void)[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
// responseData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(@"didReceiveData %@", data);
(void)[self.image initWithData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
//[textView setString:@"Unable to fetch data"];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"Succeeded! Received image data");
}
@end
My issue is that even though the connection:didReceiveData: method is called and it prints the data to the console, the [self.image initWithData:data] does not seem to be loading the image into the view. What is the problem here?
There are at least two mistakes in your code.
The first mistake is that you should not be calling
[self.image initWithData]as all init methods are meant to be called once, and during construction of an object, right after the alloc:The second mistake is that the method above is incremental, and can be called multiple times before the full image is received. What you want to do instead is store your data in a NSMutableData object (or similar) until all data has been received, and create an image once you get the message:
You will probably need to use something other than a category to do this properly, as you’d probably need new properties.