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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16453655/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 23:31:35  来源:igfitidea点击:

Objective C: Downloading File With Progress Bar

iosobjective-cdownloaduiprogressview

提问by SeongHo

I am trying to put a progress bar that syncs during the download that is happening. My app now can download a file using with this codes...

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

    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];

During the process of this code the app stopped during download, is it normal? Now what I want is to put a progress bar during that stop time while downloading.

在这段代码的过程中,应用程序在下载过程中停止了,这正常吗?现在我想要的是在下载时在停止时间内放置一个进度条。

I tried looking into the codes I found online but I'm a bit confused, I think I need a step-by-step-well-explained reference.

我试着查看我在网上找到的代码,但我有点困惑,我想我需要一个循序渐进的解释清楚的参考。

回答by Lithu T.V

Using AFNetworking,

使用AFNetworking

here progress is the UIProgressview

这里的进度是 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];

}

Using NSURLConnection

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

回答by Nithinbemitk

Use ASIHTTPRequest.h class and ASINetworkQueue.h for downloading the file.

使用 ASIHTTPRequest.h 类和 ASINetworkQueue.h 下载文件。

and use this code for progress bar

并使用此代码作为进度条

    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];

this may help you

这可能会帮助你

回答by Inder Kumar Rathore

First of all you should be clear whether to make a synchronous call or asynchronous. For mobile apps or any other app asynchronous is preferred one.

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

Once you are clear use NSURLConnectionclass to fetch the data from the URL. Here is the good tutorial.

一旦你明确使用NSURLConnection类从 URL 中获取数据。这是很好的教程

And for loading you can start progress while starting the request and stop it when you receive connection:didFailWithError:or connectionDidFinishLoading:delegate method.

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

回答by waterforest

I'm afraid it's not normal, use asynchronous method to get the NSData.

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