2012-07-19 46 views
3

我有以下几个问题,这导致我现在几个星期的问题。当下载文件时,NSURLConnection在文件结尾处没有调用didFinishLoading,当下载暂停并恢复时

我有一个下载文件的小框架。这个框架有能力暂停和恢复一个文件下载。 目前为止这么好。 问题是,每次我暂停下载,然后在恢复之后,负责下载的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]; 
    } 
} 

回答

2

如何计算您的预计文件中的代码尺寸?

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

+1

Thx。这确实解决了我的问题。发生这种情况时,你只需要一些代码而不用重新检查它。 – Maverick1st 2012-07-19 09:58:07

相关问题