简体   繁体   中英

How to create a UIImage from Facebook response data?

I use the following code to download the profile picture from a Facebook user's friends array:

NSString *urlString = friendData[@"picture"][@"data"][@"url"];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]
                                                          cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                      timeoutInterval:2.0f];
[NSURLConnection sendAsynchronousRequest:urlRequest 
                                   queue:[NSOperationQueue mainQueue] 
                       completionHandler:^(NSURLResponse *resp, NSData *data, NSError *error) {
    UIImage *image = [UIImage imageWithData:data];
}];

urlString is valid, ie I can open it in Safari, and I do see the picture there.

In the completion handler, error is nil , and data has 1583 bytes.
However, image is initialized as nil , ie image could not be initialized from the specified data.

What is wrong with my code?

EDIT (due to the comment of rckoenes):

resp contains the following data:

{ status code: 200, headers {
    "Access-Control-Allow-Origin" = "*";
    "Cache-Control" = "max-age=1209600, no-transform";
    "Content-Length" = 1583;
    "Content-Type" = "image/jpeg";
    Date = "Thu, 01 Oct 2015 09:19:41 GMT";
    Expires = "Thu, 15 Oct 2015 08:08:18 GMT";
    "Last-Modified" = "Thu, 01 Oct 2015 06:36:27 GMT";
    "timing-allow-origin" = "*";
} }

Try this code

Download AsyncImageView Class Here

.M File

#import "AsyncImageView.h"

NSString *urlString = friendData[@"picture"][@"data"][@"url"];

AsyncImageView *DescimageRight = [[AsyncImageView alloc]initWithFrame:CGRectMake(4,4,146,146)];
DescimageRight.contentMode = UIViewContentModeScaleAspectFill;
DescimageRight.backgroundColor=[UIColor clearColor];
DescimageRight.tag=999;
DescimageRight.imageURL=[NSURL URLWithString:urlString];
[self.view addSubview:DescimageRight];

I found the problem:

The code is correct, and the image is also loaded correctly.

The problem was that I set a breakpoint to the last line of the code, ie to

}]; // breakpoint was set here

Apparently, when the debugger stops there, it left already the scope of the completion handler, and image was already nil .
After I inserted a dummy statement behind the assignment to image , and set the breakpoint to this dummy statement, everything was OK.

Sorry for bothering you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM