在模拟器中确定但在ios设备中抛出异常

时间:2013-09-01 10:24:35

标签: iphone ios json ipad ios-simulator

当我在模拟器中运行我的应用程序时,一切都运行正常。但是当我在Ipad异常中运行相同的应用程序时会被抛出。

由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'data parameter is nil 。     在我的应用程序中,我必须请求一个web-URl并需要解析返回的JSON响应。但我检查了网址,并且能够在模拟器中完美解析。但所有问题都出现在真正的ios设备中。但我认为我已经确定了错误的代码。

+ (NSDictionary*) getParsedJSON:(NSString*) urlString {
NSLog(@"################################################################################");
NSLog(@"getParsedJSON => urlString:");
NSLog(@"%@", urlString);

NSURL* url = [NSURL URLWithString:urlString];
NSURLRequest* request = [NSURLRequest requestWithURL:url];

NSURLResponse *response1 = nil;
NSError *error = nil;

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

//NSData* response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSLog(@"--------------------------------------------------------------------------------");
NSString* responseString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSLog(@"getParsedJSON => responseString:\n%@", responseString);
NSLog(@"--------------------------------------------------------------------------------");
NSError* jsonParsingError = nil;
NSDictionary* parsedJSON = [NSJSONSerialization JSONObjectWithData:response options:0 error:&jsonParsingError]; // here is place where exception seems to be thrown.
if (jsonParsingError) {
    NSLog(@"ERROR in parsing JSON: %@", jsonParsingError);
} else {
    NSLog(@"getParsedJSON => parsedJSON: \n%@", [parsedJSON description]);
}
NSLog(@"################################################################################");    
return parsedJSON;

}

我已经确定了它似乎错误的行。我还附上了异常报告的屏幕截图。screenshot of the console。希望得到经验丰富的回复。

3 个答案:

答案 0 :(得分:1)

首先,你需要在Xcode中设置一个异常断点 - 这里有很多关于如何做到这一点的帖子。其次,在创建或返回对象的每个语句之后,添加一个断言:

NSURL *foo = ...
assert(foo);

这样做可以帮助您找到第一个问题,而不是最后一个问题。

答案 1 :(得分:1)

我们可以从日志中看到,当您在设备上使用它时,您的响应字符串为空。这可能是由于某些互联网访问问题。尝试使用:

if([response isequaltostring:@"(null)"]||response == nil || response.length == 0)
{
NSError* jsonParsingError = nil;
NSDictionary* parsedJSON = [NSJSONSerialization JSONObjectWithData:response options:0 error:&jsonParsingError]; // here is place where exception seems to be thrown.
if (jsonParsingError) {
NSLog(@"ERROR in parsing JSON: %@", jsonParsingError);
} 
else {
NSLog(@"getParsedJSON => parsedJSON: \n%@", [parsedJSON description]);
     }
}

还尝试添加特殊断点并发布应用程序崩溃的位置。 让我知道结果。

答案 2 :(得分:0)

根据您的日志,您的回复字符串为空!

做以下两件事!

  • 添加NSLog(@“响应数据:%@”,响应);并检查回复是否有价值?
  • 如果'response'有值,请将其转换为字符串 - 记录字符串值 - 并检查任何键是否具有nil值?

'NSJSONSerialization JSONObjectWithData'方法如果找到任何具有nil值的键,则会崩溃。