2013-05-09 14 views
17

Tôi đang cố gắng đặt thanh tiến trình đồng bộ hóa trong quá trình tải xuống đang diễn ra. Ứng dụng của tôi bây giờ có thể tải về một tập tin sử dụng với mã này ...Mục tiêu C: Tải xuống tệp có thanh tiến trình

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

Trong quá trình mã này ứng dụng dừng lại trong khi tải về, nó là bình thường không? Bây giờ những gì tôi muốn là đặt một thanh tiến trình trong thời gian dừng đó trong khi tải xuống.

Tôi đã thử tìm kiếm các mã tôi tìm thấy trực tuyến nhưng tôi hơi bối rối, tôi nghĩ mình cần một tài liệu tham khảo từng bước được giải thích kỹ lưỡng.

Trả lời

59

Sử dụng AFNetworking,

đây tiến bộ là UIProgressview

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

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

    [email protected]"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]; 

} 

Sử dụng 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; 
} 
+0

nó cho biết AFURLConnectionOperation là một định danh không khai báo – SeongHo

+0

Đã chỉnh sửa câu trả lời.Để bao gồm #import trong tiêu đề lớp –

+0

Tôi đã thử nó nhưng nó không được tìm thấy. Tôi nên sử dụng khung gì? – SeongHo

0

Tôi e rằng nó không bình thường, sử dụng phương pháp không đồng bộ để lấy NSData.

1

Sử dụng lớp ASIHTTPRequest.h và ASINetworkQueue.h để tải xuống tệp.

và sử dụng mã này cho thanh tiến trình

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

này có thể giúp bạn

+0

tôi nên đặt này trên nút bấm vào nút "Tải xuống"? – SeongHo

+0

có bạn muốn đặt mã này vào chức năng bấm nút ... – Nithinbemitk

0

Trước hết bạn phải rõ ràng cho dù để thực hiện cuộc gọi đồng bộ hoặc không đồng bộ. Đối với ứng dụng dành cho thiết bị di động hoặc bất kỳ ứng dụng nào khác không đồng bộ được ưu tiên nhất.

Khi bạn sử dụng rõ ràng NSURLConnection lớp để tìm nạp dữ liệu từ URL. Đây là good tutorial.

Và để tải, bạn có thể bắt đầu tiến trình trong khi bắt đầu yêu cầu và dừng nó khi bạn nhận được connection:didFailWithError: hoặc connectionDidFinishLoading: phương thức ủy quyền.

+0

Cách tải xuống tệp pdf đồng bộ bằng NSURLConnection trong nhanh chóng @Inder Kumar Rathore –