3

我有以下问题,现在让我发疯了好几个星期。

我有一个用于下载文件的小框架。该框架具有暂停和恢复文件下载的能力。到现在为止还挺好。问题是,每次我暂停下载然后,在我恢复它之后,如果下载的字节等于预期的文件大小,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];
    }
}
4

1 回答 1

2

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

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

于 2012-07-19T09:52:04.573 回答