在目标 C 中使用 JSON 格式的 webService
Posted
技术标签:
【中文标题】在目标 C 中使用 JSON 格式的 webService【英文标题】:Consume webService in JSON in objective C 【发布时间】:2017-01-13 23:25:13 【问题描述】:我有这段代码可以在 ios8 和 iOS10 中使用,但在 iOS9 中不可用
BOOL blnAnswer = NO;
NSString *strAnswer = @"";
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://10.16.2.42/api/IniciarSesionMobile/GetConnectTest"]
cachePolicy:NSURLRequestReturnCacheDataElseLoad
timeoutInterval:35];
// Fetch the JSON response
NSData *urlData;
NSURLResponse *response;
NSError *error;
// Make synchronous request
urlData = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];
// Construct a String around the Data from the response
strAnswer = [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];
【问题讨论】:
NSURLConnection 在 iOS 9 中已被弃用。它应该仍然可以工作,但你不应该将它用于新的开发。请改用 NSURLSession。 你能不能少含糊? “它有效......不是”可以是任何东西。你有没有在调试器中逐步完成它?你看过错误变量吗?是否有任何您不希望出现的变量 NIL? ***.com/questions/15749486/… 这个链接会有所帮助 【参考方案1】:如果您想从服务器获取数据,请按照以下步骤操作
NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://10.16.2.42/api/IniciarSesionMobile/GetConnectTest"]];
//If you have parameters,pass it to URL
//create the Method "GET"
[urlRequest setHTTPMethod:@"GET"];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
NSString *strResponse = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(@"response is: %@", strResponse );
];
[dataTask resume];
Get and Post
【讨论】:
现在我得到了这个“应用程序传输安全已阻止明文 HTTP (http://) 资源加载,因为它不安全。可以通过应用程序的 Info.plist 文件配置临时异常。” ***.com/questions/31254725/…以上是关于在目标 C 中使用 JSON 格式的 webService的主要内容,如果未能解决你的问题,请参考以下文章
如何使用目标 C 将 JSON 响应存储到 NSPredicate 中?