0

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???
}
Josh
  • 745
  • 1
  • 7
  • 22

1 Answers1

0

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];
}
picciano
  • 22,341
  • 9
  • 69
  • 82
  • I thought of that but how can I get the `NSData` from that method? its only available in the `connection:didReceiveData:` right ? – Josh Jun 15 '15 at 22:51
  • I implemented your methods, but I also added in a `NSLog` in the `connectionDidFinishLoading` and it instantly returns nil when run? Why is this happening? – Josh Jun 15 '15 at 23:01