iPhone Development: Load images asynchronously from server in IOS

In iPhone app development, most of time database for the app is remotely located or you can say a central database is used.If app stores user profile information then there must be 80% chances that every user of the app has its profile pic associated with his/her account.

There are lot of techniques that allows you to load images asynchronously in your app. In this post i am going to tell how you can download image from server using NSThread so that your main thread won’t get freezes. If you tried to load image on main thread then your app will become unresponsive to user till the time image load gets completed.

To load image asynchronously, we will use NSThread method called

+ (void)detachNewThreadSelector:(SEL)aSelector toTarget:(id)aTarget withObject:(id)anArgument

As per Apple Inc. documentation for iOS, descriprtion of parametres is
aSelector:The selector for the message to send to the target. This selector must take only one argument and must not have a return value.
aTarget:The object that will receive the message aSelector on the new thread.
anArgument:The single argument passed to the target. May be nil.

Below is the code that fulfill our need

 NSMutableArray *array = [[NSMutableArray alloc]initWithCapacity:0];
    [array addObject:[NSString stringWithFormat:@”http://graph.facebook.com/%@/picture?width=320&height=320″,[friendDict objectForKey:@”FriendFacebookID”]]];
    [array addObject:personImageView];
    [NSThread detachNewThreadSelector:@selector(loadImage:) toTarget:self withObject:array];
    [array release];
    array = nil;

In the above code, first we need an array so that we can send our object to loadImage method.
Then, we add url for image at first index, imageview at second index and finally call our detachNewThreadSelector method of NSThread class.

Let’s implement loadImage method

     NSMutableArray *array =(NSMutableArray *)sender;
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[array objectAtIndex:0]]];
    UIImageView *img = [array objectAtIndex:1];
    img.image=[UIImage imageWithData:data];
    data = nil;

In loadImage, first we get our array in form of sender and typecast it. Then we fetch image data by using NSData class method dataWithContentOfURL, passing url to it that is coming to us at first index of our array.Then we created an instance of UIImageView by passing it  second index object of our array.Finally, we gave it image by using the data.