1

我正在使用以下代码从 url 下载 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];
}
4

3 回答 3

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);
}
于 2013-04-18T12:25:57.910 回答
0

如果这样做curl -vvv -o epub.pdf http://www.feedbooks.com/book/3471.epub,您将看到以下行:

Content-Length: 603244

content-length 标头是您正在下载的数据的字节大小。您可以在编写数据时使用它来跟踪进度。

使用您当前的代码,您无法真正做您想做的事。您应该查看此答案以获取更多信息。

于 2013-04-18T12:14:43.963 回答
0

您可以检查dataNSData 的长度。然后你会发现实际下载的数据。

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

    [receivedData appendData:data];
}

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

它可能会帮助你。

于 2013-04-18T12:30:07.343 回答