【问题标题】:Consume webService in JSON in objective C在目标 C 中使用 JSON 格式的 webService
【发布时间】: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?
  • stackoverflow.com/questions/15749486/… 这个链接会有所帮助

标签: ios objective-c json web-services


【解决方案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 文件配置临时异常。”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-18
相关资源
最近更新 更多