UIImage returns null first time, until reloaded?

89 views Asked by At

I retrieve NSData from a url, then I try set it to an image. In the console it returns null, however when I request the data and set the image again, the image than loads?

Why do does this have to be done twice for it to load??

This is the two methods I use to get the picture.

-(void)getUserPicture {
//Grab and upload user profile picture
imageData = [[NSMutableData alloc] init]; // the image will be loaded in here
NSString *urlString = [NSString stringWithFormat:@"http://graph.facebook.com/%@/picture?type=large", userId];
NSMutableURLRequest *urlRequest =
[NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]
                        cachePolicy:NSURLRequestUseProtocolCachePolicy
                    timeoutInterval:3];

NSURLConnection *urlConnection = [[NSURLConnection alloc] initWithRequest:urlRequest
                                                                 delegate:self];
if (!urlConnection) NSLog(@"Failed to download picture");
}



-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    userPicture = [UIImage imageWithData:data];
    NSLog(@"%@",userPicture); //returns null in console first time, until reloaded???
}
1

There are 1 answers

2
picciano On BEST ANSWER

The connection:didReceiveData: method is called repeatedly as the data is loaded incrementally. You probably want the connectionDidFinishLoading: method instead.

By the way, you'll still likely need a connection:didReceiveData:, but rather than trying to create the image, you'll just be appending the new data to a buffer. Then in the connectionDidFinishLoading: method, you take the buffer and create your image.

Example code, but please add error handling as needed:

@property (strong, nonatomic) NSMutableData *data;

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    self.data = [NSMutableData data];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [self.data appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    self.userPicture = [UIImage imageWithData:self.data];
}