1

想要使用带有 AFNetworking 的 json 从 iOS 传递 NSArray 或 NSDitory 到 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) {

                 }
         ];
4

2 回答 2

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];
于 2013-10-21T05:09:47.020 回答
0

您需要添加这行代码来正确初始化 AFHTTPClient:

[client setParameterEncoding:AFJSONParameterEncoding];
于 2013-10-21T06:38:59.783 回答