如何以同步方式发布JSON数据?可以使用NSURLSession或AFNetworking或其他方式吗?
答案 0 :(得分:0)
使用同步
将数据发布到服务器的示例基本代码//PASS YOUR URL HERE
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"your URL"]];
//create the Method "POST" for posting data to server
[request setHTTPMethod:@"POST"];
//Pass The String to server like below
NSString *strParameters =[NSString strin gWithFormat:@"user_email=%@&user_login=%@&user_pass=%@& last_upd_by=%@&user_registered=%@&",txtemail.text,txtuser1.text,txtpass1.text,txtuser1.text,datestr,nil];
//Print the data that what we send to server
NSLog(@"the parameters are =%@", strParameters);
//Convert the String to Data
NSData *data1 = [strParameters dataUsingEncoding:NSUTF8StringEncoding];
//Apply the data to the body
[request setHTTPBody:data1];
//Create the response and Error
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *resSrt = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];
//This is for Response
NSLog(@"got response==%@", resSrt);
if(resSrt)
{
NSLog(@"got response");
}
else
{
NSLog(@"faield to connect");
}
答案 1 :(得分:0)
在 user3182143 的回答中,最新版本的iOS 9中不推荐sendSynchronousRequest
。
您可以使用NSURLSession
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:[NSURL URLWithString:londonWeatherUrl]
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error) {
NSString *strResult = [[NSString alloc]initWithData:data encoding:NSASCIIStringEncoding];
}] resume];
答案 2 :(得分:0)
这是我的解决方案:
- (IBAction)postJSONSynchronization:(id)sender {
__block BOOL success = NO;
__block NSDictionary *jsonDic = nil;
NSURLSession *session = [NSURLSession sharedSession];
// 创建请求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.url]];
request.HTTPMethod = @"POST"; // 请求方法
NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
[parameters setObject:@13577766655 forKey:@"phoneNumber"];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil];
request.HTTPBody = jsonData; // 请求体
NSCondition *condition = [[NSCondition alloc] init];
// 创建任务
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(@"Child Thread:%@",[NSThread currentThread]);
if (!error) {
jsonDic = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
success = YES;
} else {
NSLog(@"%@",error);
}
[condition lock];
[condition signal];
[condition unlock];
}];
[task resume];
// 启动任务
NSLog(@"Main Thread:%@",[NSThread currentThread]);
[condition lock];
[condition wait];
[condition unlock];
NSLog(@"测试时机");
NSLog(@"josnDic:%@",jsonDic);}