- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我的 iOS 应用正在获取内部代码(例如 101),并通过该代码读取服务器上的 JSON 文件(例如 101.json)并读取内部数据。一切都运行良好,但是如果服务器上没有文件(用于该代码)(现在它只是在找不到文件时不显示任何数据)并且没有互联网连接只是为了从应用程序内的 JSON 文件获取数据,该怎么办?这是我的代码:
NSString *baseURLStr = @"http://myserverurl/";
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL
URLWithString:[baseURLStr stringByAppendingFormat:@"%d/%d.json", int1, int2]]];
NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil error:nil];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
我发现了如何在没有互联网连接的情况下读取应用程序中的文件。
if (data == nil){
NSData *data = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"FAILED" ofType:@"json"]];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
self.members = json[@"data"];
}
else {
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
self.members = json[@"data"];
}
最佳答案
您可能需要检查三种类型的问题:
连接错误:检查以确保连接没有失败;如果失败,数据将为 nil
并且 NSError
对象将被填充;典型原因是 URL 中的服务器名称无效、服务器已关闭或根本没有互联网连接);
HTTP 错误:如果执行 HTTP 请求,您想检查网络服务器是否报告成功检索页面/资源,即您收到 HTTP 状态代码 200;错误条件的示例可能是 404 - 未找到错误(请参阅 HTTP Status Code Definitions 以获得更完整的列表);和
服务器代码错误:检查以确保服务器以有效的 JSON 响应,即检查收到的响应是否可以成功解析为 JSON(您要确保有生成 JSON 的服务器代码没有问题,例如服务器代码中的错误)。
因此:
NSURLRequest *request = nil;
NSURLResponse *response = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];
if (!data) {
NSLog(@"%s: sendSynchronousRequest error: %@", __FUNCTION__, error);
return;
} else if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
if (statusCode != 200) {
NSLog(@"%s: sendSynchronousRequest status code != 200: response = %@", __FUNCTION__, response);
return;
}
}
NSError *parseError = nil;
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
if (!dictionary) {
NSLog(@"%s: JSONObjectWithData error: %@; data = %@", __FUNCTION__, parseError, [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
return;
}
// now you can use your `dictionary` object
显然,如果它是 NSArray,请将上面的 JSONObjectWithData
行更改为返回数组,但概念是相同的。
或者,更好的是,使用异步连接(因为你不应该在主队列上使用同步连接):
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (!data) {
NSLog(@"%s: sendAynchronousRequest error: %@", __FUNCTION__, connectionError);
return;
} else if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
if (statusCode != 200) {
NSLog(@"%s: sendAsynchronousRequest status code != 200: response = %@", __FUNCTION__, response);
return;
}
}
NSError *parseError = nil;
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
if (!dictionary) {
NSLog(@"%s: JSONObjectWithData error: %@; data = %@", __FUNCTION__, parseError, [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
return
}
// now you can use your `dictionary` object
}];
// Note, with asynchronous connection, do not try to use `data`
// or the object you parsed from theJSON after the block, here.
// Use it above, inside the block.
关于objective-c - NSURLConnection 获取 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20995815/
我正在寻找有关使用 NSURLConnection 异步请求的好教程。我一直在 stackoverflow 和谷歌中四处寻找,但找不到。这可能是无数类似此处问题的重复。但请指导我正确的教程,我以前使用
我在植入简单的 NSURLConnection 时遇到了这个奇怪的问题... 调用了 didReceiveData 方法,我很乐意尝试附加接收数据,但是... nada! 肯定有一些数据(如长度所示,
我是 iOS 互联网连接的新手。 我正在尝试从特殊站点获取数据。 以下代码适用于所有站点以查看 url 中的数据。 但是,如果我将其更改为特殊站点以获取他们的数据,它将返回 NULL! 我认为该站点如
在 iOS 9 中,我将 NSURL 与 NSURLConnection 一起使用,对于一个特定的 URL,它在 - (void)connection:(NSURLConnection *)conne
多个 NSURLConnections 正在启动(在单个 UIViewController 中)以收集不同类型的数据。当他们返回(-connectionDidFinishLoading)时,我想根据到
谁能帮助我理解这些问题:使用 Alamofire 优于 NSURLSession/NSURLConnection 有什么优势? NSURLSession 和 NSURLConnection 有什么区别
是否可以取消 NSURLConnection开始于 sendAsynchronousRequest:queue:completionHandler: ? 为什么不sendAsynchronousReq
你好, 我正在试验一个非常恶性的崩溃,它在设备日志中以下列方式显示: Exception Type: EXC_BAD_ACCESS (SIGSEGV) Exception Codes: KERN_I
这是一个开放性问题,旨在了解什么是我认为可能很常见的问题的最佳实践或最常见的解决方案。 假设我有一个要下载的 URL 列表;该列表本身托管在服务器上,因此我启动了一个 NSURLConnection
我基本上将RestKit与RKClient一起使用,并执行get请求。我的系统使用用户名/密码/帐户来认证用户。它只是用于用户名/密码的httpbasic,而帐户只是一个子域。 我的问题是,如果执行以
我尝试使用 [sendSynchronousRequest: returnedResponse: error:] 代码连接服务器,但证书未经验证,导致出现错误。我已经读过 How to use NSU
我正在使用 NSURLConnection 通过 GET 请求与服务器连接。要登录,我将发送带有表单 url 的 GET 请求 http://:@my.serverurl.com/user/login
我正在将图像上传到我的服务器,当我上传图像时,我试图向用户显示上传进度条。但在 NSURLConnection 委托(delegate)方法 连接中: didSendBodyData:totalByt
这是另一个简单的问题,我在 Google 上搜索了一个小时后却找不到答案... 用户正在文本字段中输入内容,当该字段失去焦点时,我启动 NSURLConnection.... NSString *us
我正在尝试验证连接是否成功,但得到的结果不稳定。当我尝试使用虚假网址执行同步请求时: NSData *responseData = [NSURLConnection sendSynchronousRe
我正在将图像加载到 iPhone 上的图库中,但遇到了问题。显然,当尝试从互联网下载图像时,脚本中的某些内容对文件名中的空格不满意。 这是连接线。 NSURLConnection *conn = [[
我有一个 NSURLConnection,每次调用 -(void)viewWillAppear:animated 时都会调用它(仅用于测试) 我就是这样做的 receivedData = [[NSMu
在 NSURLConnection 上调用实例方法 cancel 通常根本不会取消连接。 我正在 NSOperation 中执行异步 NSURLConnection。如果取消操作,则通过调用 NSUR
当我允许加载完成时,我有一个 NSURLConnection 工作正常。但是如果用户点击后退按钮,意味着 webview 将消失,我想取消正在进行的 NSURLConnection。但是,如果在调用
我的客户端应用程序中有一个使用 NSURLConnection 的小错误。我已经追踪到一个意外的连接保持事件,这似乎使网络服务器感到困惑(可能是服务器端的错误)。解决方法是在某个时刻强制关闭所有未完成
我是一名优秀的程序员,十分优秀!