如何使用NSURLSESSION通过mvc控制器Web服务从json post方法返回数据?
问题描述:
首先请的,点击这个link然后...如何使用NSURLSESSION通过mvc控制器Web服务从json post方法返回数据?
我如何得到这个输出,如姓名,STD &分配到文本框,我已经在Xcode 5做到了这一点,但NSURLConnection的在Xcode 7.2未使用所以使用NSURLSESSION我如何绑定到文本框?
NSError *error = nil;
NSMutableDictionary *dic2 = [[NSMutableDictionary alloc] init];
[dic2 setObject:@"324" forKey:@"grno"];
NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
[dic setObject:@"RestAPI" forKey:@"interface"];
[dic setObject:@"StudentLogin" forKey:@"method"];
[dic setObject:dic2 forKey:@"parameters"];
NSData *postData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&error];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://ios.skyzon.in/STudent/STudentDetail"]];
[req setHTTPMethod:@"POST"];
[req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[req setHTTPBody:postData];
NSURLSessionDataTask * dataTask =[defaultSession dataTaskWithRequest:req
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(@"Response:%@ %@\n", response, error);
if(error == nil)
{
// NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
// NSLog(@"Data = %@",text);
NSMutableDictionary *responseDic = [[NSMutableDictionary alloc]init];
responseDic = [NSJSONSerialization JSONObjectWithData:postData options:NSJSONReadingAllowFragments error:&error];
NSLog(@"%@",responseDic);
self.txt.text = [responseDic objectForKey:@"Name"];
NSLog(@"%@",[responseDic objectForKey:@"Name"]);
}
}];
[dataTask resume];
答
你可以像你这样的NSURLSESSION。
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString:@"http://ios.skyzon.in/STudent/STudentDetail"] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(@"%@", json);
self.txt.text = [responseDic objectForKey:@"Name"];
}];
可能会帮助你。