代码实现:
(进度条的实质也是一个UIView)
#import "ViewController.h"
@interface ViewController ()<NSURLSessionDownloadDelegate>
// 全局的网络会话
@property (nonatomic ,strong)NSURLSession *session;
@property (nonatomic ,strong)UIView *progressView;
@end
@implementation ViewController
-(UIView *)progressView
{
if (!_progressView) {
_progressView = [[UIView alloc] init];
_progressView.backgroundColor = [UIColor greenColor];
_progressView.alpha = 0.5;
[self.view addSubview:_progressView];
}
return _progressView;
}
// 懒加载
-(NSURLSession *)session
{
if (!_session) {
NSURLSessionConfiguration *cgf = [NSURLSessionConfiguration defaultSessionConfiguration];
_session = [NSURLSession sessionWithConfiguration:cgf delegate:self delegateQueue:nil];
}
return _session;
}
// 开始下载的时候,需要一个下载任务!
- (IBAction)start:(id)sender {
NSURL *url = [NSURL URLWithString:@"http://localhost/resources.zip"];
NSURLSessionDownloadTask *task = [self.session downloadTaskWithURL:url];
[task resume];
}
- (IBAction)pause:(id)sender {
}
- (IBAction)resum:(id)sender {
}
- (void)viewDidLoad {
[super viewDidLoad];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(30, 50, 320, 30)];
label.text = @"这里是";
label.backgroundColor = [UIColor redColor];
label.textAlignment = NSTextAlignmentCenter;
label.alpha = 0.5;
[self.view addSubview:label];
}
#pragma NSURLSessionDownloadDelegate
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location
{
NSLog(@"下载完毕");
}
// 监听下载进度
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didWriteData:(int64_t)bytesWritten
totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
float progress = (float)totalBytesWritten/totalBytesExpectedToWrite;
dispatch_async(dispatch_get_main_queue(), ^{
// 显示进度条
self.progressView.frame = CGRectMake(30, 50, progress*320, 30);
});
}
@end