Search code examples
iphoneobjective-ciosipadasihttprequest

ASIHTTPRequest Send Data With Each Request


I have an array which includes URLs of JSON feeds. I am using ASIHTTPRequest to download the feed and process it. Each feed contains several JSON entries or objects. The request downloads the data and selects only one object and stores it.

The feeds URLs look like this: http:www.*.com/id.json, where id is some string. After downloading the data and selecting the object, I'd like to store the id in a dictionary as a key that maps to a value of the object downloaded.

How can I pass that string with the request? So for example:

ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
request.tag = 3;
[request setDelegate:self];
[request startAsynchronous];

Now in requestFinished, I can identify that request as follows: if (request.tag == 3. Along with tag of 3, I'd like to send the ID. So I can do something with it in if (request.tag == 3). Is there some property where I can pass a string or any data along with a request?


Solution

  • You can pass your own dictionary of data in the userInfo property, which, like the tag property, can be read back on the request after receiving the response.

    NSString* jsonId = @"1234";
    request.userInfo = [NSDictionary dictionaryWithObject:jsonId forKey:@"id"];
    

    See documentation.

    If you need to handle success and failure on many different types of request, you have several options:

    1. If your requests are all of the same broad type, but you want to distinguish between them, you can set the userInfo NSDictionary property of each request with your own custom data that you can read in your finished / failed delegate methods. For simpler cases, you can set the request’s tag property instead. Both of these properties are for your own use, and are not sent to the server.

    2. If you need to handle success and failure in a completely different way for each request, set a different setDidFinishSelector / setDidFailSelector for each request


    If you want to post data like a web page posts a form, you can use the ASIFormDataRequest subclass. It makes it very easy to send POST requests with strings you add individually:

    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    [request setPostValue:@"Ben" forKey:@"first_name"];
    [request setPostValue:@"Copsey" forKey:@"last_name"];
    

    See the documentation.