0

我正在使用以下内容来请求数据NSJSONSerialization。我遇到的问题是,如果数据无法访问(例如没有网络连接),应用程序就会崩溃。如果网络或服务器出现故障,我该如何阻止应用程序崩溃?

我正在[self requestData];调用viewDidLoad:方法

-(void)requestData {

    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL
                                                          URLWithString:@"http://example.com/api/nodes"]];

    NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

    NSError *jsonParsingError = nil;

    NSDictionary *publicData =  [NSJSONSerialization JSONObjectWithData:response
                                                                options:0
                                                                  error:&jsonParsingError];
    publicDataArray = [publicData objectForKey:@"data"];
    for(publicDataDict in publicDataArray) {
        NSLog(@"data output is %@",[publicDataDict objectForKey:@"title"]);

    }
}

谢谢你的帮助

4

2 回答 2

3

一些想法:

  1. 使用可达性检查网络连接
  2. 始终使用异步请求,否则它将阻止您的 UI,直到应用程序从服务器获得响应。
  3. 始终使用异常处理

这里的问题是:

您正在using中调用synchronous请求。但是服务器宕机了,所以你不会得到结果,它仍然期待任何数据到来。但在该请求完成之前,您的应用不会加载。由于这个跳板 application-watchdog 将终止您的应用程序。viewDidLoadsendSynchronousRequest

什么是看门狗

看门狗——为了让用户界面保持响应,iOS 包含一个看门狗机制。如果您的应用程序未能及时响应某些用户界面事件(启动、暂停、恢复、终止),则看门狗将终止您的应用程序并生成看门狗超时崩溃报告。看门狗给你的时间没有正式记录,但它总是少于网络超时。

请在 Apple 网站上查看此技术问题。

于 2013-06-12T09:51:54.540 回答
1

你为什么不检查是否[NSURLConnection sendSynchronousRequest:]有任何错误?

NSError *requestError = nil;
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&requestError];

if (requestError)
{
    NSLog(@"sync. request failed with error: %@", requestError);
}
else
{
    // handle data
}

你真的应该检查是否NSJSONSerialization也有错误:

NSError *jsonParsingError = nil;

NSDictionary *publicData =  [NSJSONSerialization JSONObjectWithData:response
                                                            options:0
                                                              error:&jsonParsingError];
if (jsonParsingError)
{
    NSLog(@"JSON parsing failed with error: %@", jsonParsingError);
}
else
{
    // do something
}
于 2013-06-12T09:54:02.660 回答