JSON返回空崩溃应用
问题描述:
我有一些代码使用Dribbble API来返回一个Shot,但是,如果JSON中的任何数据是空的,应用崩溃,我试图实现并捕获,如果它是null继续前进,但这似乎不起作用。请有人建议?JSON返回空崩溃应用
非常感谢
詹姆斯
self.JSONString = [NSString stringWithFormat:@"http://api.dribbble.com/shots/1970521"];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:self.JSONString]];
__block NSDictionary *json;
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (data != nil) {
json = [NSJSONSerialization JSONObjectWithData:data
options:0
error:nil];
NSLog(@"Async JSON: %@", json);
}
else {
return;
}
}];
答
您需要妥善处理连接错误。 尝试类似这样:
self.JSONString = [NSString stringWithFormat:@"http://api.dribbble.com/shots/1970521"];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:self.JSONString]];
__block NSDictionary *json;
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
{
if (connectionError != nil || data == nil)
{
NSLog(@"Error loading dribble shot: %@",connectionError);
//TODO: Show an alert to the user with UIAlertView?
}
else
{
NSError *jsonParsingError = nil;
json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonParsingError];
if (jsonParsingError != nil || json == nil){
NSLog(@"Error parsing JSON: %@",jsonParsingError);
//TODO: User alert?
}
else
{
NSLog(@"Parsed JSON: %@",json);
//Process parsed JSON, update UI, etc.
//Keep in mind updates to the UI should be done in a main-thread call like this:
dispatch_sync(dispatch_get_main_queue(),^{
//Update UI here
});
}
}
}
}];
答
您可以使用第三方Dribbble iOS SDK。它包装所有Dribbble API,提供单行api调用方法,还包含OAuth2集成流和数据模型类。检出:https://github.com/agilie/dribbble-ios-sdk
在处理'null'的'json'后,您的应用必须崩溃。解决方法是[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];无法解析您的数据,原因可能是传递给它的非UTF数据。 – iphonic 2015-03-13 10:31:59
/questions/5716942/touchjson-dealing-with-nsnull – Wain 2015-03-13 10:31:59
您应该将XCode调试器附加到您的应用程序并发布崩溃回溯,否则很难为您提供帮助。抛出异常吗?它是什么样的崩溃? – Bensge 2015-03-13 10:36:10