Is there an event for when a UIImage has finished loading
ios, objective-c, uiimage
Solution
in your `.h`
@interface YourClass : YourSuperclass<NSURLConnectionDataDelegate>
@property (nonatomic) NSMutableData *imageData;
@property (nonatomic) NSUInteger totalBytes;
@property (nonatomic) NSUInteger receivedBytes;
And somewhere call
NSURL *imageUrl = [[NSURL alloc]initWithString:@"http://..."];
NSURLRequest *request = [NSURLRequest requestWithURL: imageUrl];
NSURLConnection *connection = [NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
And also implement the delegate methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) urlResponse;
NSDictionary *dict = httpResponse.allHeaderFields;
NSString *lengthString = [dict valueForKey:@"Content-Length"];
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
NSNumber *length = [formatter numberFromString:lengthString];
self.totalBytes = length.unsignedIntegerValue;
[self.imageData = [[NSMutableData alloc] initWithLength:self.totalBytes];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.imageData appendData:data];
self.receivedBytes += data.length;
// Actual progress is self.receivedBytes / self.totalBytes
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
imageView.image = [UIImage imageWithData:self.imageData];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
//handle error
}
Update:
Since `NSMutableData initWithLength:` creates a data object whose raw data is filled with zeros, replace `initWithLength:` with just `init` and it will works.
Problem
I am displaying a UIImage view with this code: ``` NSURL *imageUrl = [[NSURL alloc]initWithString:@"http://..."]; NSData *imageData = [[NSData alloc] initWithContentsOfURL:imageUrl]; UIImage *audioArt =[[UIImage alloc] initWithData:imageData]; UIImageView *artView =[[UIImageView alloc] initWithImage:audioArt]; artView.contentMode = UIViewContentModeScaleAspectFit; artView.autoresizesSubviews = NO; artView.frame = viewRef.bounds; [artView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight]; [artView setBackgroundColor:[UIColor blackColor]]; [viewRef setBackgroundColor:[UIColor blackColor]]; [viewRef addSubview:artView]; ``` Is there an event in Objective C to tell when this UIImage has finished loading or when the UIImageView has finished displaying the image? Many thanks.