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???
}
The
connection:didReceiveData:
method is called repeatedly as the data is loaded incrementally. You probably want theconnectionDidFinishLoading:
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 theconnectionDidFinishLoading:
method, you take the buffer and create your image.Example code, but please add error handling as needed: