目标C:使用进度条下载文件

时间:2013-05-09 03:05:07

标签: ios objective-c download uiprogressview

我正在尝试设置一个在正在进行的下载过程中同步的进度条。 我的应用程序现在可以使用此代码下载文件...

    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 个答案:

答案 0 :(得分: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 :(得分: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];

这可能会对你有所帮助

答案 2 :(得分:0)

我担心这不正常,使用异步方法获取NSData。

答案 3 :(得分:0)

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

一旦明确,请使用 NSURLConnection 类从URL中获取数据。 这是good tutorial

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