利用NSURLSessionDownLoadDelegate做简单的下载进度条






代码实现:

(进度条的实质也是一个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


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值