XMLReader crashes when no internet connection
My app needs to get data from a webpage that is in XML format. I am using XMLReader to do this and the function works great when there is internet access, however the specific line
NSArray *arr = [XMLReader objectsForXMLData:receivedData error:parseError];
crashes when there is no internet. I want the app to print out an error message when there is no internet. Thus i am using **parseError as an indicator. However, i am unsure why the app crashes when it executes this line. I posted th开发者_如何学Ce function below. Thank you for all of your help in advance.
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;
Check for the presence of 'receivedData' before using.
// 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;
}
You can handle the Exception with a try/catch, if there is no internet conection you will receive the exception. I Think that is the correct way
@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];
}
精彩评论