gpt4 book ai didi

iphone - 下载文件时,NSURLConnection 不会在文件末尾调用 didFinishLoading,当下载暂停并恢复时

转载 作者:搜寻专家 更新时间:2023-10-30 20:20:51 26 4
gpt4 key购买 nike

我有以下问题,这让我抓狂了几个星期。

我有一个用于下载文件的小型框架。该框架具有暂停和恢复文件下载的能力。到目前为止,一切都很好。问题是,每次我暂停下载然后恢复下载后,负责下载的 NSURLConnection 不会调用 connectionDidFinishLoading,如果下载的字节等于预期的文件大小,但保持在调用 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

的代码
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
amountDownloaded += data.length;
NSInteger receivedLen = [data length];
bytesReceived = (bytesReceived + receivedLen);
if(expectedSize != NSURLResponseUnknownLength) {
progress = ((bytesReceived/(float)expectedSize)*100)/100;
[self performSelectorOnMainThread:@selector(updateProgressBar) withObject:nil waitUntilDone:NO];
percentComplete = progress*100;
}

if (self.savePath == nil || [self.savePath isEqualToString:@""]) {
[self.downloadData appendData:data];
}
else {
[self.downloadData appendData:data];
NSFileHandle *handle = [NSFileHandle fileHandleForWritingAtPath:self.savePath];
[handle seekToEndOfFile];
[handle writeData:data];
//
}
if (expectedSize < bytesReceived)
{
NSLog(@"download exceeded expected size %f with %lld", expectedSize, bytesReceived);
[self pause];
[self cancel];
self.connection = nil;
self.downloadData = nil;
bytesReceived = 0;
expectedSize = 0;
amountDownloaded = 0;
progress = 0;
percentComplete = 0;
[self start];
}
}

最佳答案

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

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

关于iphone - 下载文件时,NSURLConnection 不会在文件末尾调用 didFinishLoading,当下载暂停并恢复时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11556820/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com