![](/img/trans.png)
[英]AFJSONRequestOperation crashing with “data parameter is nil” NSJSONSerialization error
[英]How to handle NSJSONSerialization's crashing when disconnected to internet
我在我的应用程序中实现了 Web 服务。 我的方式很典型。
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//Web Service xxx,yyy are not true data
NSString *urlString = @"http://xxx.byethost17.com/yyy";
NSURL *url = [NSURL URLWithString:urlString];
dispatch_async(kBackGroudQueue, ^{
NSData* data = [NSData dataWithContentsOfURL: url];
[self performSelectorOnMainThread:@selector(receiveLatest:) withObject:data waitUntilDone:YES];
});
return YES;
}
- (void)receiveLatest:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions
error:&error];
NSString *Draw_539 = [json objectForKey:@"Draw_539"];
....
控制台错误信息:
*由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“数据参数为零”
当我的 iphone 连接到 Internet 时,该应用程序成功运行。 但是,如果它断开与 Internet 的连接,应用程序将在NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
你能告诉我如何处理这个错误吗? NSError
有用吗?
该错误告诉您“responseData”为零。 避免异常的方法是测试“responseData”,如果它为零则不调用 JSONObjectWithData。 相反,您应该对这种错误情况做出反应。
在将其传递给JSONObjectWithData:options:error:
方法之前,您不会检查您的responseData
是否为零。
可能你应该试试这个:
- (void)receiveLatest:(NSData *)responseData {
//parse out the json data
NSError* error;
if(responseData != nil)
{
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions
error:&error];
NSString *Draw_539 = [json objectForKey:@"Draw_539"];
}
else
{
//Handle error or alert user here
}
....
}
EDIT-1:对于良好的实践,您应该在JSONObjectWithData:options:error:
方法之后检查此error
对象,以检查 JSON 数据是否已成功转换为 NSDictionary
- (void)receiveLatest:(NSData *)responseData {
//parse out the json data
NSError* error;
if(responseData != nil)
{
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions
error:&error];
if(!error)
{
NSString *Draw_539 = [json objectForKey:@"Draw_539"];
}
else
{
NSLog(@"Error: %@", [error localizedDescription]);
//Do additional data manipulation or handling work here.
}
}
else
{
//Handle error or alert user here
}
....
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.