3

currently i want to get facebook profile picture then convert the picture into CCSprite.

so far my code look like this :

//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];

it works, but it's taking a while before loaded, about few seconds.

my question is, aside from internet connection, is there any better approach to load facebook profile image as fast as possible? thanks

2 Answers2

7

You put the network code in the main thread, which would block the UI and own bad user experience. Regularly, you should put such things in another thread. Try to use dispatch

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];
    });
});

Or if you like you can try JBAsyncImageView. Maybe you have to hack it to your CCSprite :)

onevcat
  • 4,591
  • 1
  • 25
  • 31
  • thanks, there's no UI lag anymore. is this called asynchronous programming? any good source to read for this in objective-c? – user1606616 Dec 06 '12 at 03:55
  • 1
    Yes, it's called [GCD(Grand Central Dispatch)](https://developer.apple.com/library/mac/#documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html). You may want to check [Paul's iOS course](https://itunes.apple.com/itunes-u/ipad-iphone-application-development/id473757255?mt=10) as a starting point. [Block and Multithreading](https://itunes.apple.com/cn/podcast/10.-blocks-multithreading/id473757255?i=107327893&mt=2) is for this – onevcat Dec 06 '12 at 04:56
1

For one I would opt for using AFNetworking to asynchronously request the image data. My guess is that this is what's causing the delay. You may notice your UI locks up during those few seconds. Asynchronously calling that data will resolve this. Even better, you may consider using Facebook's iOS SDK to call the image.

Pouria Almassi
  • 1,580
  • 2
  • 17
  • 26