我想從服務器的一個網址數組中逐一下載多個文件。使用NSURLSession下載多個文件
我需要顯示每個下載文件的進度,其中用戶也可以取消它。
ViewControllerh:
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController {
IBOutlet UIView *vw_download;
IBOutlet UILabel *lbl_BookTitle;
IBOutlet UILabel *lbl_BookDes;
IBOutlet UILabel *lbl_downloadStatus;
IBOutlet UIImageView *img_todownload;
IBOutlet UIProgressView *vw_downloadbar;
IBOutlet UIButton *btn_stopDownload;
}
-(IBAction)btn_stopDownloading:(id)sender;
@end
ViewController.m:
#import "ViewController.h"
@interface ViewController()<NSURLSessionDelegate> {
NSMutableArray *downloadLinksArray;
NSURLSession *session ;
NSURLSessionDownloadTask *task;
}
@end
@implementation ViewController
- (void)viewDidLoad {
downloadLinksArray=[[NSMutableArray alloc]initWithObjects:@"URL1",@"URL2", @"URL3", @"URL4", nil];
[vw_downloadbar setProgress:0];
lbl_downloadStatus.text=[NSString stringWithFormat:@"Downloading in Progress"];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
-(IBAction)startDownload:(id)sender {
//[self startChapterDownLoad];
for (int i=0;i< [downloadLinksArray count];i++) {
NSURL *Url= [NSURL URLWithString:[NSString stringWithFormat:@"%@",[downloadLinksArray objectAtIndex:i]]];
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:[NSOperationQueue mainQueue]];
NSURLRequest* request = [NSURLRequest requestWithURL:Url];
task = [session downloadTaskWithRequest:request];
[task resume];
}
}
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
CGFloat percentDone = (double)totalBytesWritten/(double)totalBytesExpectedToWrite;
// Notify user.
[self performSelectorOnMainThread:@selector(updateProgress:) withObject:[NSNumber numberWithFloat:percentDone] waitUntilDone:NO];
}
- (void) updateProgress:(NSNumber *)percent {
[vw_downloadbar setProgress:percent.floatValue];
}
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
// Either move the data from the location to a permanent location, or do something with the data at that location.
}
-(IBAction)btn_stopDownloading:(id)sender {
[task cancel];
[vw_downloadbar setProgress:0];
}
好的,那麼問題是什麼,你沒有輸入任何問題? – 2017-04-06 03:49:59
版主只能糾正拼寫錯誤和語法相關的錯誤。 #keep_calm –