Search code examples
iosxcodefacebooknsdata

Make fetching of images faster from facebook in iOS


Hi, I'm trying to fetch the user's friends profile pic from facebook and load it in my table and it works fine, but however it takes a long time based on number of friends you have I have noticed that in my fetchPeopleimages function the part of [NSData dataWithContentsOfURL:imageURL] is making the delay. I've searched through stackoverflow and it seems that I may have to implement the NSURLConnection sendAsynchronousRequest method or cache. But there is no proper example. Can anyone please provide a solution to this? If I have to implement those methods please do give a example on how should I implement it in my code.

-(void) fetchPeopleimages
{
 if ([listType isEqualToString:@"Facebook"])
    {
        int count=0;
        NSMutableArray *imageArray=[[NSMutableArray alloc]initWithCapacity:[_peopleImageList count]];

        for(NSString *imageUrl in _peopleImageList)
        {
            NSData *imageData = nil;
            NSString *imageURLString = imageUrl;
            count++;
            NSLog(@"URL->%@,count->%d", imageURLString,count);

            if (imageURLString)
            { //This block takes time to complete
                NSURL *imageURL = [NSURL URLWithString:imageURLString];
                imageData = [NSData dataWithContentsOfURL:imageURL];
            }
            if (imageData)
            {
                [imageArray addObject:imageData];
            }
            else
            {
                [imageArray addObject:[NSNull null]];
            }

        }

    _peopleImageList=imageArray;
        NSLog(@"%@",_peopleImageList);
    }
}

Solution

  • Never ever use __withContentsOfURL in an iOS app. As you can see, it blocks the thread it runs on, making your app appear jerky or unresponsive. If you're really lucky, the iOS watchdog timer will kill your app if one of those operations takes too long.

    You must use an asynchronous network operation for something like this.

    Apple has a sample app that does exactly this: https://developer.apple.com/library/ios/samplecode/LazyTableImages/Introduction/Intro.html