目前我想获取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];
它可以工作,但是在加载之前需要一段时间,大约几秒钟。
我的问题是,除了互联网连接,有没有更好的方法尽快加载Facebook个人资料图片?感谢
答案 0 :(得分:7)
您将网络代码放在主线程中,这将阻止用户界面并拥有糟糕的用户体验。通常,你应该把这些东西放在另一个线程中。尝试使用调度
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];
});
});
或者如果您愿意,可以尝试JBAsyncImageView。也许你必须将其破解为你的CCSprite:)
答案 1 :(得分:1)
首先,我会选择使用AFNetworking异步请求图像数据。我的猜测是,这是导致延迟的原因。您可能会注意到在几秒钟内UI被锁定。异步调用该数据将解决此问题。更好的是,您可以考虑使用Facebook's iOS SDK来调用图像。