Ali Shahid
Ali Shahid

Reputation: 516

How to send array of elements from iOS to PHP webservice

I want to send array of <Full name, Email> pairs to my php webservice. Should I use NSMutable array of dictionaries? What is the proper way?

Update:

I want to send in JSON.

Upvotes: 0

Views: 1249

Answers (3)

CoderSpinoza
CoderSpinoza

Reputation: 2165

You can just pass dictionary as parameters so that your php script grabs those parameters with $_POST variable.

I will post a sample code which uses AFNetworking library.

NSArray *keys = [NSArray arrayWithObjects: @"key1", @"key2", nil];
NSArray *values = [NSArray arrayWithObjects: @"value1", @"value2", nil];
NSDictionary *parameters = [NSDictionary dictionaryWithObjects: values Keys: keys];

AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL[NSURL URLWithString:@"Your  server url"];
NSURLRequest *request = [client requestWithMethod:@"POST" path:@"path" parameters:parameters];

AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
}];
[operation start];

AFNetworking class takes care of everything for you. Generally, it is better to enqueue these operations in a NSOperationQueue. Hope that helps!

Upvotes: 1

Prateek Prem
Prateek Prem

Reputation: 1544

Use this logic:

NSDictionary *dic = [NSDictionary dictionaryWithObject:yourDictionary/Array forKey:@"yourkeyForWebServiceFile"];
                SBJsonWriter *json=[[SBJsonWriter alloc] init];
                NSString *jsonStr = [json stringWithObject:dic];

now send this jsonStr in your PHP file as Post request. I have used SBJson library in this you can use others also.

Upvotes: 0

Harish
Harish

Reputation: 1519

If it's going to be JSON formatted data use dictionaries. Look into AFNetworking library which handles all of your networking calls asynchronously for you.

Upvotes: 0

Related Questions