NSURLConnection不调用didFailWithError。

问题描述:

我正在尝试编写一些代码来检查数据源的URL,然后使用该URL中的对象填充数组。它实际上运行良好,但如果网络连接或地址有问题,我想用捆绑文件中的数据填充数组。我遇到的问题是从未调用connection didFailWithError方法。我尝试传递一个简单的字符串,但它不会调用。我希望应用程序仍可以用于正在使用iPod touch或处于飞行模式的用户。NSURLConnection不调用didFailWithError。

connection didReceiveResponse正在工作没有问题。

这就是我正在使用的。

- (void)loadListData{ 
NSLog(@"Loading data from sources"); 

NSURLRequest *listURLRequest = [NSURLRequest requestWithURL:integerPhoneListURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:1.0]; 
[[NSURLConnection alloc] initWithRequest:listURLRequest delegate:self]; 

    if (!listConnectFail){ 
     phoneListJSON =[NSData dataWithContentsOfURL:integerPhoneListURL]; 
     [self performSelectorOnMainThread:@selector(fetchedData:) withObject:phoneListJSON waitUntilDone:YES]; 


    } else { 
     //This will tell us if there is an error loading the file 
     NSLog(@"File not found on web init from file"); 
     phoneListJSON =[NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"contactlist" ofType:@"json"]]; 
     [self performSelectorOnMainThread:@selector(fetchedData:) withObject:phoneListJSON waitUntilDone:YES]; 
    } 



//Initialize the filtered list with array of customer objects. Based on original data 
filteredList = [[NSMutableArray alloc] init]; 

for (NSDictionary *dict in phoneListOriginal) { 
    contact *single = [[contact alloc] init]; 
    single.fName = [dict objectForKey:@"fName"]; 
    single.lName = [dict objectForKey:@"lName"]; 
    single.extension = [dict objectForKey:@"extension"]; 
    single.title = [dict objectForKey:@"title"]; 
    single.department = [dict objectForKey:@"department"]; 
    single.cellNumber = [dict objectForKey:@"cellNumber"]; 
    //NSLog(@"%@", single.lName); 
    [filteredList addObject:single]; 
} 


NSLog(@"Array filteredLIst contains %d records",[filteredList count]); } 

- (无效)连接:(NSURLConnection的*)连接didFailWithError:(NSError *)错误{

listConnectFail = YES; 
NSLog(@"Connection Failed, pulling from file"); } 

- (无效)连接:(NSURLConnection的*)连接didReceiveResponse:(NSURLResponse *)响应{listIdctFail = NO; NSLog(@“连接成功,从API填充”); }

我知道这可能是一些愚蠢的事,我没有看到,但我可以使用帮助,看看有什么我不事先

谢谢!

你是如何确认你的代表没有收到消息的?你检查了日志吗?

您的代码似乎认为'listConnectFail'将在NSURLConnection的init完成后立即设置,但不一定如此。

[[NSURLConnection alloc] initWithRequest:listURLRequest delegate:self]; 
if (!listConnectFail){...} 

NSURLConnection文档指出'代理将在加载过程中接收委托消息。'

但是,我不确定飞机模式,也许这个特定的错误可以同步检测到。

+0

该日志不给我很多信息。如果我给它一个错误的URL,它就会等待几秒钟没有消息,直到最终中断并抛回'SIGABRT' – Tenthrow 2012-04-10 20:25:17