Objective C:使用进度条下载文件

19

我正在尝试添加一个在下载时同步的进度条。我的应用程序现在可以使用以下代码下载文件...

    pdfData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:@"http://webaddress.com/pro/download/file.pdf"]];

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

    pdfFilePath = [resourcePDFPath stringByAppendingPathComponent:@"myPDF.pdf"];

    [pdfData writeToFile:pdfFilePath atomically:YES];
在代码处理过程中,应用程序在下载期间停止了,这正常吗?现在我想在下载停止时间期间放置一个进度条。
我尝试查找了一些在线代码,但有些困惑,我认为我需要一个逐步详细解释的参考资料。
4个回答

60

使用AFNetworking

这里使用UIProgressView来显示进度。

#import <AFNetworking/AFNetworking.h>//add to the header of class

-(void)downloadShowingProgress
{
   progress.progress = 0.0;

    currentURL=@"http://www.selab.isti.cnr.it/ws-mate/example.pdf";


    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:currentURL]];
    AFURLConnectionOperation *operation =   [[AFHTTPRequestOperation alloc] initWithRequest:request];

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"MY_FILENAME_WITH_EXTENTION.pdf"];
    operation.outputStream = [NSOutputStream outputStreamToFileAtPath:filePath append:NO];

    [operation setDownloadProgressBlock:^(NSUInteger bytesRead, NSUInteger totalBytesRead, NSUInteger totalBytesExpectedToRead) {
        progress.progress = (float)totalBytesRead / totalBytesExpectedToRead;

    }];

    [operation setCompletionBlock:^{
        NSLog(@"downloadComplete!");

    }];
    [operation start];

}

使用NSURLConnection

-(void)downloadWithNsurlconnection
{

    NSURL *url = [NSURL URLWithString:currentURL];
    NSURLRequest *theRequest = [NSURLRequest requestWithURL:url         cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];
    receivedData = [[NSMutableData alloc] initWithLength:0];
    NSURLConnection * connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self     startImmediately:YES];


}


- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    progress.hidden = NO;
    [receivedData setLength:0];
    expectedBytes = [response expectedContentLength];
}

- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [receivedData appendData:data];
    float progressive = (float)[receivedData length] / (float)expectedBytes;
    [progress setProgress:progressive];


}

- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

}

- (NSCachedURLResponse *) connection:(NSURLConnection *)connection willCacheResponse:    (NSCachedURLResponse *)cachedResponse {
    return nil;
}

- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:[currentURL stringByAppendingString:@".mp3"]];
    NSLog(@"Succeeded! Received %d bytes of data",[receivedData length]);
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    [receivedData writeToFile:pdfPath atomically:YES];
    progress.hidden = YES;
}

1
它表示 AFURLConnectionOperation 是未声明的标识符。 - SeongHo
编辑了答案。必须在类头文件中包含 #import <AFNetworking/AFNetworking.h>。 - Lithu T.V
1
在标题 AFNetworking 中添加了框架链接。 - Lithu T.V
正如其名称所示,它是要接收的总字节数。 - Lithu T.V
说实话,我之前不知道NSURLResponse有一个expectedContentLength属性。以前我是先进行HEAD请求,然后再进行GET请求...但考虑到HTTP的工作原理,这是有道理的... - Nate Symer
显示剩余9条评论

1
使用ASIHTTPRequest.h类和ASINetworkQueue.h下载文件。
并使用以下代码来实现进度条。
    request = [ASIHTTPRequest requestWithURL:@"http://webaddress.com/pro/download/file.pdf];
    [request setDelegate:self];
    [request setDownloadProgressDelegate:progressView];
    [request setShowAccurateProgress:YES];
    request.shouldContinueWhenAppEntersBackground=YES;
    request.allowResumeForFileDownloads=YES;
    [request startAsynchronous];

这可能会帮助您。

我应该将这个放在“下载”按钮的点击事件上吗? - SeongHo
是的,您想将此代码放在按钮单击函数中... - Nithinbemitk

0

恐怕这不是正常的,使用异步方法获取NSData。


0

首先,您应该清楚是要进行同步调用还是异步调用。 对于移动应用或任何其他应用程序,异步调用是首选。

一旦您明确了使用 NSURLConnection 类从 URL 获取数据。 这里有一个好的教程

对于加载,您可以在开始请求时启动进度,并在收到connection:didFailWithError:connectionDidFinishLoading:委托方法时停止它。


如何在Swift中使用NSURLConnection同步下载PDF文件@Inder Kumar Rathore - McDonal_11

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接