我的应用需要从XML格式的网页获取数据。我正在使用XMLReader来执行此操作,并且当有Internet访问时,该功能很有用,但是具体的行
NSArray *arr = [XMLReader objectsForXMLData:receivedData error:parseError];
没有互联网时崩溃。我希望应用程序在没有互联网时打印出错误信息。因此我使用** parseError作为指标。但是,我不确定为什么应用程序在执行此行时崩溃。我发布了以下功能。感谢您提前提供的所有帮助。
NSDateFormatter *dateFmt = [[NSDateFormatter alloc] init];
dateFmt.timeStyle = NSDateFormatterNoStyle;
dateFmt.dateFormat = DATADATEFRMT; // @"yyyy-MM-dd";
NSMutableString *urlStr = [NSMutableString stringWithString:[DATASRCWCAT stringByAppendingString:cat]];
category = cat;
NSLog(@"cate = %@",cat);
[urlStr appendFormat:@"%@%@%@%@", DATAPRD, dataPeriod, DATASTDATE, [dateFmt stringFromDate:currDate]];
NSLog(@"dataPeriod = %@", [dateFmt stringFromDate:currDate]);
NSString *urlString = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//NSLog(@"URL to obtain data: %@", urlString);
self.crimeid = cat;
// Get the data in xml format and parse
NSData *receivedData = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];
NSError **parseError = nil;
NSArray *arr = [XMLReader objectsForXMLData:receivedData error:parseError]; // <---- crashes here with no internet access.
//NSLog(@"array = %@", [arr objectAtIndex:1]);
self.crimeDataArray = arr;
答案 0 :(得分:3)
使用前检查是否存在'receivedData'。
// Get the data in xml format and parse
NSData *receivedData = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];
if ( receivedData ) // Will only get here if there's data
{
NSError **parseError = nil;
NSArray *arr = [XMLReader objectsForXMLData:receivedData error:parseError]; // <---- crashes here with no internet access.
//NSLog(@"array = %@", [arr objectAtIndex:1]);
self.crimeDataArray = arr;
}
答案 1 :(得分:1)
您可以使用try / catch处理异常,如果没有互联网连接,您将收到异常。我认为这是正确的方法
@try {
NSData *data= [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];
NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Conection found",nil) message:@"Conection found" delegate:nil cancelButtonTitle:NSLocalizedString(@"Ok",nil) otherButtonTitles:nil ,nil];
[alert show];
}
@catch (NSException *exception) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"NO Conection found" message:@"No Conection found" delegate:nil cancelButtonTitle:NSLocalizedString(@"Ok",nil) otherButtonTitles:nil ,nil];
[alert show];
}