如何将 NSArray 或 NSDitory 从 iOS 发送到 PHP webservice
Posted
技术标签:
【中文标题】如何将 NSArray 或 NSDitory 从 iOS 发送到 PHP webservice【英文标题】:How to send NSArray or NSDictory from iOS to PHP webservice 【发布时间】:2013-10-21 05:04:07 【问题描述】:想要使用带有 AFNetworking 的 json 从 ios 向 php WebServer 传递 NSArray 或 NSDitory
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)
];
【问题讨论】:
【参考方案1】: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];
【讨论】:
如果此答案有助于解决您的问题,请接受此答案,以便其他人可以得到解决方案。【参考方案2】:需要添加这行代码才能正确初始化AFHTTPClient:
[client setParameterEncoding:AFJSONParameterEncoding];
【讨论】:
以上是关于如何将 NSArray 或 NSDitory 从 iOS 发送到 PHP webservice的主要内容,如果未能解决你的问题,请参考以下文章
来自 plist 文件的 NSArray 或 NSDictionary
如何从 NSDictionary 中获取 NSArray 名称?