NSURLConnection不调用didFailWithError。

时间:2012-04-10 19:54:40

标签: error-handling timeout nsurlconnection nsurlconnectiondelegate

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

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]); }

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {

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

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {     listConnectFail = NO;     NSLog(@“连接成功,从API填充”); }

我知道这可能是我看不到的愚蠢,但我可以使用帮助看看我不知道

提前致谢!

1 个答案:

答案 0 :(得分:0)

您是如何确认您的代表未收到该消息的?你查了一下日志吗?

您的代码似乎假设在NSURLConnection的init完成后会立即设置'listConnectFail',但情况不一定如此。

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

NSURLConnection文档声明'委托将在加载过程中收到委托消息。'

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