下载文件NSURLConnection在文件末尾没有调用didFinishLoading,当下载暂停并恢复时

时间:2012-07-19 08:27:50

标签: iphone objective-c ios download nsurlconnection

我有以下问题让我疯了几个星期。

我有一个用于下载文件的小框架。该框架能够暂停和恢复文件下载。 到现在为止还挺好。 问题是,每次我暂停下载然后,在我恢复后,负责下载的NSURLConnection将不会调用connectionDidFinishLoading,如果下载的字节等于预期的文件大小,但继续调用{{1}因此破坏了我的下载。 我不知道为什么会这样。当我不暂停/恢复下载时,一切正常。 以下是暂停和恢复下载的方法代码。

connectionDidReceiveData

如果有人可以帮助我,我会很高兴。

我已经测试过,如果已下载的数据大小正确,那么就是这样。一切似乎都没问题。

非常感谢提前。 特立独行

=========编辑=========

以下是我- (id)pause { [self.connection cancel]; self.connection = nil; return self; } - (id)resume { NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:self.url cachePolicy:NSURLCacheStorageAllowed timeoutInterval:600]; NSFileManager *manager = [NSFileManager defaultManager]; NSString *localSavePath = self.savePath; if (failBlocks.count > 0) { [self cancel]; [self start]; } else { if( ![manager fileExistsAtPath:localSavePath] ) { [manager createFileAtPath:localSavePath contents:[NSData data] attributes:nil]; } if (self.downloadData.length > 0) { log_muma2(@"Should resume url %@",self.url); // Define the bytes we wish to download. NSString *range = [NSString stringWithFormat:@"bytes=%i-", downloadData.length]; [request setValue:range forHTTPHeaderField:@"Range"]; } if (!self.connection) { NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self]; self.connection = conn; } } return self; }

的代码
didReceiveData

1 个答案:

答案 0 :(得分:2)

如何计算预期的文件大小?

如果您使用response.expectedContentLength,请注意每次重新开始下载时初始化新连接时此值都会减少。