NSURLConnection获取JSON文件 [英] NSURLConnection getting JSON File

查看:108
本文介绍了NSURLConnection获取JSON文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的iOS应用正在获取内部代码(例如101),并通过该代码读取服务器上的JSON文件(例如101.json)并读取内部数据.一切工作正常,但是如果服务器上没有文件(针对该代码)(现在如果没有找到文件就不显示数据)并且没有互联网连接只是为了从应用程序内的JSON文件中获取数据,该怎么办?这是我的代码:

My iOS app is getting the code inside (ex. 101), and by that code it reads JSON file (ex. 101.json) on server and read the data inside. Everything is working good, but how to do that if there's no file (for that code) on server (now it's just showing no data if file not found) and if there's no internet connection just to get data from JSON file inside the app? Here's my code:

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];  

我了解了在没有互联网连接的情况下如何在应用程序内读取文件.

I found out how to read the file inside the app if there's no internet connection.

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"];

}  

推荐答案

您可能需要检查三种类型的问题:

There are three types of issues you might want to check for:

  • 连接错误:检查以确保连接没有失败;如果确实失败,则数据将为nil,并且将填充NSError对象;典型的原因是网址中的服务器名称无效,服务器已关闭或根本没有Internet连接);

  • Connection errors: Check to make sure the connection didn't fail; if it did fail, the data will be nil and the NSError object would be populated; typical causes would be an invalid server name in the URL, server was down, or no internet connection at all);

HTTP错误::如果执行HTTP请求,则要检查Web服务器是否报告成功检索页面/资源,即您收到的HTTP状态码为200;错误情况的示例可能是404-未找到错误(请参见 HTTP状态代码定义以获得更完整的列表);和

HTTP errors: If doing a HTTP request, you want to check that the web server reported success retrieving the page/resource, namely that you received HTTP status code of 200; an example of an error condition might be a 404 - not found error (see the HTTP Status Code Definitions for more complete list); and

服务器代码错误::检查以确保服务器使用有效的JSON进行了响应,即检查是否可以成功将收到的响应解析为JSON(您要确保存在生成JSON的服务器代码中没有问题,例如服务器代码中的错误).

Server code errors: Check to make sure the server responded with valid JSON, i.e. check to see if the response received can be parsed as JSON successfully (you want to make sure there was no problem in the server code that generated the JSON, e.g. a mistake in your server code).

因此:

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行上方的内容更改为return array,但是概念是相同的.

Obviously, if it was NSArray, change that above JSONObjectWithData line to return array, but the concept is the same.

或者更好的方法是使用异步连接(因为您永远不要在主队列上使用同步连接):

Or, better, use asynchronous connection (as you should never use synchronous connections on the main queue):

[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.

这篇关于NSURLConnection获取JSON文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆