Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ASIHTTPRequest to POST nested params using a NSDictionary

Trying to post information for nested parameters to a rails app and having some trouble.

#pragma mark - Begin Network Operations
- (void)beginNetworkOperation {
    NSURL *requestURL = [NSURL URLWithString:[self retrieveURL]];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:requestURL];

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0
    [request setShouldContinueWhenAppEntersBackground:YES];
#endif

    [request setRequestMethod:@"PUT"];

    [request addRequestHeader:@"Content-Type" value:@"application/json"];

    [request addPostValue:strClientId forKey:@"client_id"];
    [request addPostValue:strAccessToken forKey:@"access_token"];

    NSDictionary *assetDictionary = [NSDictionary dictionaryWithObject:self.tags forKey:@"tags"];
    [request addPostValue:assetDictionary forKey:@"asset"];

    [request setDelegate:self];
    [request setDidFinishSelector:@selector(requestFinished:)];
    [request setDidFailSelector:@selector(requestFailed:)];
    [request startSynchronous];
}

self.tags is just a NSString with comma separated values, however once arriving at the rails server the tags parameter cannot be read (params[:asset][:tags]).

like image 777
Kyle Avatar asked Oct 10 '22 13:10

Kyle


2 Answers

Try to pass you dictionary as a JSON string and not a dictionary object.

You can do that using iOS5 JSON library, or this one for more compatibility:

https://github.com/stig/json-framework

What I do is use appendPostData because I am pretty sure that setting the header (addRequestHeader) and using addPostValue are not compatible functions. Here is an example of my code:

ASIFormDataRequest *request;
[request addRequestHeader:@"Content-Type" value:@"application/json"];
[request appendPostData:[[SBJsonWriter new] dataWithObject:myDictionaryToPassAsAnArgument]];

When you use appendPostData, you can't use any addPostValue. You have to put everything in the dictionary.

like image 59
MatLecu Avatar answered Oct 13 '22 11:10

MatLecu


Here is snippet of working code with JSONKit on iOS.

[request addRequestHeader:@"Content-Type" value:@"application/json"];

NSMutableDictionary *requestDict = [[NSMutableDictionary alloc] init];
[requestDict setObject:@"iSteve" forKey:@"UserId"];
[requestDict setObject:@"1" forKey:@"CompanyCode"];
[requestDict setObject:@"IN" forKey:@"LineOfBusiness"];
[requestDict setObject:@"M" forKey:@"LineOfBusinessClassification"];
[requestDict setObject:pricingVariablesListString forKey:@"CarQuoteString"];
[request appendPostData:[requestDict JSONData]];
like image 24
Sanjer Avatar answered Oct 13 '22 10:10

Sanjer