gpt4 book ai didi

ios - 如何获取文件大小以了解是否下载?

转载 作者:行者123 更新时间:2023-11-29 11:00:30 27 4
gpt4 key购买 nike

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

最佳答案

使用 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];
}

委托(delegate)方法

- (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);
}

关于ios - 如何获取文件大小以了解是否下载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16082563/

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