2011-07-29 154 views
1

我的应用程序需要从XML格式的网页获取数据。我使用的XMLReader做到这一点,当有上网功能的伟大工程,但具体的线路当没有互联网连接时,XMLReader崩溃

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; 

回答

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; 
} 
+0

非常感谢,解决了它。 – John

1

您可以使用try/catch处理Exception,如果没有Internet连接,您将收到异常。我认为这是正确的方式

@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]; 
     } 
相关问题