美文网首页
URLSession数据协议下载图片

URLSession数据协议下载图片

作者: JohnayXiao | 来源:发表于2017-08-03 09:08 被阅读8次
    #import "ViewController.h"
    
    @interface ViewController ()<NSURLSessionDataDelegate>
    @property (weak, nonatomic) IBOutlet UIImageView *imageView;
    @property (weak, nonatomic) IBOutlet UIProgressView *progressView;
    //可变数据类型
    @property (nonatomic, strong) NSMutableData *mutableData;
    
    @end
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        //初始化可变数据对象
        self.mutableData = [NSMutableData data];
    }
    - (IBAction)downloadImageByDataDelegate:(id)sender {
        //0.创建NSURL对象
        NSURL *url = [NSURL URLWithString:@"http://images.apple.com/v/iphone-5s/gallery/a/images/download/photo_1.jpg"];
        //1.session和config结合/绑定(default:默认/缺省...)
        NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
        NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue mainQueue]];
        //2.创建数据任务
        NSURLSessionDataTask *dataTask = [session dataTaskWithURL:url];
        //3.执行任务
        [dataTask resume];
    }
    
    //delegate监听进度(周期性的触发方法)
    - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
        //data:每次服务器返回的资源的数据值
        NSLog(@"每次返回的数据大小:%lu;数据总大小:%lld", (unsigned long)data.length, dataTask.countOfBytesExpectedToReceive);
        
        //存储每次服务器返回data值
        [self.mutableData appendData:data];
        //更新imageView
        self.imageView.image = [UIImage imageWithData:self.mutableData];
        
        //更新进度
        self.progressView.progress = dataTask.countOfBytesReceived * 1.0 / dataTask.countOfBytesExpectedToReceive
        ;
    }
    //delegate下载完毕
    - (void)URLSession:(NSURLSession *)session task:(nonnull NSURLSessionTask *)task didCompleteWithError:(nullable NSError *)error {
        
    }
    
    
    @end
    
    

    相关文章

      网友评论

          本文标题:URLSession数据协议下载图片

          本文链接:https://www.haomeiwen.com/subject/cfvulxtx.html