2012-12-05 108 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來調用圖像。