2012-12-05 72 views
3

当前我想获取脸谱资料图片,然后将图片转换成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个人资料图片?谢谢

回答

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 :)

+0

谢谢,没有UI滞后了。这就是所谓的异步编程吗?在objective-c中阅读这个任何好的资源? – user1606616

+1

是的,它被称为[GCD(Grand Central Dispatch)](https://developer.apple.com/library/mac/#documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html)。您可能需要检查[Paul的iOS课程](https://itunes.apple.com/itunes-u/ipad-iphone-application-development/id473757255?mt=10)作为起点。 [Block and Multithreading](https://itunes.apple.com/cn/podcast/10.-blocks-multithreading/id473757255?i=107327893&mt=2)就是这个 – onevcat

+0

非常感谢你 – user1606616

1

对于我会选择使用AFNetworking异步请求图像数据。我的猜测是,这是造成延迟的原因。您可能会注意到您的UI在几秒钟内锁定。异步调用该数据将解决此问题。更好的是,你可以考虑使用Facebook's iOS SDK来调用图像。