Su Myat Mon
Su Myat Mon

Reputation: 31

How to send NSArray or NSDictory from iOS to PHP webservice

Want to pass NSArray or NSDictory using json with AFNetworking from iOS to PHP WebServer

NSDictionary *courseList = ........;
NSString* name = @"UserName";
NSString* password = @"Password";     
NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:
                                    name, @"UserName",
                                    password, @"Password",
                                    courseList, @"courseList",
                                    nil];
NSURL *baseURL = [NSURL URLWithString:[NSString stringWithFormat:SERVER_URL]];
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:baseURL];
        [client registerHTTPOperationClass:[AFJSONRequestOperation class]];
        [client setDefaultHeader:@"Accept" value:@"application/json"];
        [client setDefaultHeader:@"Accept-Charset" value:@"utf-8"];
        [client postPath:URL
              parameters:parameters
                 success:^(AFHTTPRequestOperation *operation, id json) {

                 }
                 failure:^(AFHTTPRequestOperation *operation, NSError *error) {

                 }
         ];

Upvotes: 1

Views: 1062

Answers (2)

Maxim Pavlov
Maxim Pavlov

Reputation: 2962

You need to add this line of code to properly initialize AFHTTPClient:

[client setParameterEncoding:AFJSONParameterEncoding];

Upvotes: 0

user1673099
user1673099

Reputation: 3289

NSDictionary * postDictionary = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"value1", @"value2", nil]
                                                                  forKeys:[NSArray arrayWithObjects:@"key1", @"key2", nil]];

NSError * error = nil;
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:postDictionary options:NSJSONReadingMutableContainers error:&error];

NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"your_webservice_post_url"]];
[urlRequest setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[urlRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setHTTPBody:jsonData];

NSURLConnection * myConnection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self startImmediately:YES];

Upvotes: 4

Related Questions