我不知道如何通过POST使用NSURLSession
将字典中的值传递到服务器中。请帮我解决这个问题。
我的词典包含联系信息(仅限姓名和电话号码),其中密钥是此人的姓名,值是他们的电话号码。
我有使用nsurl连接的示例代码 - 如何将其转换为使用NSURLSession
?
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://holla.com/login"]];
request.HTTPMethod = @"POST"; [request setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@"212333333",@"ABCD",@"6544345345",@"NMHG", nil];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil];
request.HTTPBody = jsonData;
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
答案 0 :(得分:4)
我使用以下方法解决问题:
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL * url = [NSURL URLWithString:[ NSString stringWithFormat:@"http://holla.com/login/save_contact"]];;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setHTTPMethod:@"POST"];
NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys:@"212333333",@"ABCD",@"6544345345",@"NMHG",
nil];
NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error];
[request setHTTPBody:postData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
if(error == nil)
{
NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(@"Data = %@",text);
}
}];
[postDataTask resume];