如何获取文件大小以确定是否下载?

时间:2013-04-18 12:08:41

标签: ios objective-c progress-bar download file-handling

我正在使用以下代码从网址下载epub / pdf。我喜欢提供进度条,所以当我开始下载时会显示进度,下载完成后会弹出一条消息。我该如何实现呢?

我的下载文件代码

-(void)Download
 {
    NSData *pdfData = [[NSData alloc] initWithContentsOfURL:[NSURL    URLWithString:@"http://www.feedbooks.com/book/3471.epub"]];

    //Store the Data locally as epub  File if u want pdf change the file extension  

    NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle]  resourcePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"Documents"]];

    NSString *filePath = [resourceDocPath stringByAppendingPathComponent:@"3471.epub"];

    [pdfData writeToFile:filePath atomically:YES];
    NSLog(@"%@",filePath);
 }

我在我的.m文件中使用此代码,但它不适用于我

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    _totalFileSize = response.expectedContentLength;
    responseData = [[NSMutableData alloc] init];
}


-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    _receivedDataBytes += [data length];
    MyProgressBar.progress = _receivedDataBytes / (float)_totalFileSize;
    [responseData appendData:data];
}

3 个答案:

答案 0 :(得分:2)

使用NSURLConnection

.h文件中的

double datalength;
NSMutableData *databuffer;
UIProgressView *progress;
.m文件中的

-(void)Download
{
      NSURLConnection *con=[[NSURLConnection alloc]initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.feedbooks.com/book/3471.epub"]] delegate:self startImmediately:YES];
      [con start];
}

委托方法

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    datalength = [response expectedContentLength];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [databuffer appendData:data];
    progress.progress = (databuffer.length/datalength);
    self.HUD.detailsLabelText = [NSString stringWithFormat:@"Downloading  %.f  %%",(databuffer.length/datalength)*100];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle]  resourcePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"Documents"]];
    NSString *filePath = [resourceDocPath stringByAppendingPathComponent:@"3471.epub"];
    [pdfData writeToFile:filePath atomically:YES];
    NSLog(@"%@",filePath);
}

答案 1 :(得分:0)

如果你curl -vvv -o epub.pdf http://www.feedbooks.com/book/3471.epub,你会看到以下一行:

Content-Length: 603244

内容长度标头是您正在下载的数据的大小(以字节为单位)。您可以使用它来跟踪编写数据时的进度。

使用您当前的代码,您无法真正做到您想要的。您应该查看this answer以获取更多信息。

答案 2 :(得分:0)

您可以检查data长度的NSData。然后你会找到实际下载的数据。

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;
{
    // append the new data to the receivedData

    [receivedData appendData:data];
}

在这里,您将获得以字节为单位的数据长度。您可以根据需要进行转换。

它可能对你有帮助。

相关问题