iosxcodeuiimageafnetworking

How do I retrieve an image from a web server API using AFImageRequestOperation?


I'm new to AFNetworking and I'm having a hard time retrieving image data from the server I'm getting it from. I want to display an image that is stored in the web server API. This is what my URLRequest comes back with:

{
o_id: "2",
g_id: "1",
title: "Here's a new objective",
description: "This is the description",
hint: "",
target: "10",
timestamp: "2012-09-19 17:24:59",
filename: "http://uploadedimageurl.co.uk/view/uploads/obj_2_1351788537.jpg",
image_width: "600",
active: "1",
group_name: "Test Group",
n_insights: "15",
n_comments: "0",
unixtimestamp: 1348071899,
}

I want to retrieve the image inside filename: I'm just drawing a blank on how I'd go about doing this. I've had a go at using AFImageRequestOperation but I'm not sure I'm on the right track - I'll display what I have so far...

NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/api/groups/get/1",URL_ROOT]];
    AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
    NSURLRequest *request = [httpClient requestWithMethod:@"GET" path:nil parameters:nil];
 AFImageRequestOperation *imageOperation = [AFImageRequestOperation imageRequestOperationWithRequest:request imageProcessingBlock:nil success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image)
    {

        
    } failure:nil];
    
    [imageOperation start];

Just looking to see whether I'm going in the right direction for retrieving this Image data but also want to know how I would retrieve the image stored in filename: Any ideas?


Solution

  • You will need to send 2 requests:

    1. AFJSONRequestOperation
    2. AFImageRequestOperation

    In the success block of the first request operation you retrieve the image url:

    NSString* filename = [JSON valueForKey:@"filename"];
    NSURL* imageURL = [NSURL URLWithString:filename];
    

    Then send the 2nd request with that URL (only if it is not nil). You receive the UIImage in the success block if the AFImageRequestOperation.