如何从iOS发送NSArray或NSDictory到PHP webservice

时间:2013-10-21 05:04:08

标签: php ios json nsdictionary afnetworking

希望使用json通过NSArray或NSDictory与AFNetworking从iOS到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) {

                 }
         ];

2 个答案:

答案 0 :(得分:4)

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];

答案 1 :(得分:0)

您需要添加以下代码行才能正确初始化AFHTTPClient:

[client setParameterEncoding:AFJSONParameterEncoding];