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

4 回答 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;
}
于 2013-05-09T05:22:39.007 回答
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];

这可能会帮助你

于 2013-05-09T03:35:46.667 回答
0

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

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

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

于 2013-05-09T04:14:46.420 回答
0

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

于 2013-05-09T03:32:34.003 回答