获取facebook个人资料图片

use*_*616 3 objective-c cocos2d-iphone ios ccsprite

目前我想获取facebook个人资料图片然后将图片转换为CCSprite.

到目前为止我的代码看起来像这样:

//fbId is facebook id of someone
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"https://graph.facebook.com/%@/picture?type=normal", fbId]];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];

//convert UIImage to CCSprite
CCTexture2D *texture = [[[CCTexture2D alloc] initWithImage:image resolutionType:kCCResolutionUnknown] retain];
CCSprite *sprite = [CCSprite spriteWithTexture:texture];
[self addChild:sprite];
Run Code Online (Sandbox Code Playgroud)

它有效,但在加载前需要一段时间,大约几秒钟.

我的问题是,除了互联网连接,有没有更好的方法尽快加载Facebook个人资料图像?谢谢

one*_*cat 7

您将网络代码放在主线程中,这将阻止UI并拥有糟糕的用户体验.通常,你应该把这些东西放在另一个线程中.尝试使用派遣

dispatch_queue_t downloader = dispatch_queue_create("PicDownloader", NULL);
dispatch_async(downloader, ^{
    NSData *data = [NSData dataWithContentsOfURL:url];
    UIImage *image = [UIImage imageWithData:data];
    dispatch_async(dispatch_get_main_queue(), ^{
        CCTexture2D *texture = [[[CCTexture2D alloc] initWithImage:image resolutionType:kCCResolutionUnknown] retain];
        CCSprite *sprite = [CCSprite spriteWithTexture:texture];
        [self addChild:sprite];
    });
});
Run Code Online (Sandbox Code Playgroud)

或者如果您愿意,可以尝试JBAsyncImageView.也许你必须将其破解为你的CCSprite :)