How to use ASIFormDataRequest for http post array of NSDictionary objects

Hey, I need to make an HTTP POST request with an array of NSDictionary objects.

However, when I do this, on the server side, I notice that the NSDictionary object is not being deserialized to hash. It deserializes to a string - this is not what I want.

This is how I send the parameter from the client side (IPhone):

ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url]; for (ABContact *c in contactsWithEmailsOrPhones){ NSString *phoneNumber = [[ABContactsHelper class] contactPhoneNumber:c]; NSString *email = [[c emailArray] objectAtIndex:0]; NSLog(@"looping: %@, %@", phoneNumber, email); NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys: phoneNumber, @"phone", email, @"email", [c firstname], @"firstname", [c lastname], @"lastname", nil]; [request addPostValue:dict forKey:@"contacts[]"]; } [request setDelegate:self]; [request startAsynchronous]; 

This is how it looks when it is deserialized on the server side (rails):

 Started POST "/app/find_friends" for 67.164.97.48 at Thu Sep 23 14:40:37 -0700 2010 Processing by app#find_friends as HTML Parameters: {"contacts"=>["{\n   email = \"xx\";\n   firstname = xx;\n   lastname = xx;\n   phone = \"xx\";\n}", "{\n   email = \"xx\";\n   firstname = xx;\n   lastname = xx;\n   phone = \"xx\";\n}"]} Completed 200 OK in 0ms (Views: 0.3ms | ActiveRecord: 0.0ms) 

I am sure that this is a common problem that people face. So there is definitely a solution for this.

Thanks for all the comments and answers.

+6
ios ruby-on-rails objective-c iphone
source share
2 answers

First, to explain what you see:

The addPostValue method is designed to accept a single value and calls [value description] to convert this value to a string. The description method gives the string representation that you see on the server side (the description method also calls NSLog if you pass it an object, so the format should look pretty familiar). Thus, the iphone was asked to send the string, and does so, and the server "correctly" shows it as a string.

If you just want to send one contact, just call 'addPostValue' for each key / value pair - that is. once for the phone, again for email, etc.

If you want to transfer multiple contacts, you probably need something better. I am not very familiar with ruby-on-rails, so there may be other solutions, but, of course, the general way to transfer more complex data structures to web services from iphone is to use json.

There is a json library for iphone here:

http://code.google.com/p/json-framework/

and rubies on rails are built into json support.

+2
source

you can do something like this

[request setPostValue:login forKey:@"user[login]"]; [request setPostValue:password forKey:@"user[password]"];

0
source

All Articles