Search code examples
objective-cioscocos2d-iphoneccsprite

get facebook profile picture


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


Solution

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