My app has to download profile pictures from facebook. The code that I wrote to download images works well with image url that has direct links (e.g.: http://www.mydomain.com/profile_picture.png)
But it produces an error for facebook urls (e.g.: http://graph.facebook.com/100000741043402/picture)
Following is the code:
NSURLRequest *imageRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:imageUrl] cachePolicy:NSURLRequestReturnCacheDataDontLoad timeoutInterval:30.0];
AFImageRequestOperation *operation = [AFImageRequestOperation imageRequestOperationWithRequest:imageRequest
imageProcessingBlock:nil
cacheName:@"nscache"
success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image){ profilePicture.image = image;
[profilePicture.layer setBorderColor: [[UIColor colorWithRed:137.0/255.0 green:137.0/255.0 blue:137.0/255.0 alpha:1.0] CGColor]];
[profilePicture.layer setBorderWidth: 2.0];
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error){ NSLog(@"%@",[error description]); }
];
[operation start];
And following is the response:
Error Domain=NSURLErrorDomain Code=-1008 "resource unavailable" UserInfo=0x97e0ae0 {NSErrorFailingURLStringKey=http://graph.facebook.com/100000741043402/picture, NSErrorFailingURLKey=http://graph.facebook.com/100000741043402/picture, NSLocalizedDescription=resource unavailable, NSUnderlyingError=0xa3559b0 "resource unavailable"}
Any tips/suggestions would be highly appreciated.
If you use curl to dump the headers of the entire HTTP conversation, you’ll see:
So FB is redirecting you to the profile picture, but NSURLRequest doesn’t follow redirects by itself. This post (Handling redirects correctly with NSURLConnection) shows how you can handle this, with the main lesson being that you have to follow the redirects until you end up with the 200 response that will indicate the terminal URL.