NSURLSession代理实现一个下载

//
//  ViewController.m
//  NSURLSessionDownloadDelegate
//
//  Created by hq on 16/4/17.
//  Copyright © 2016年 hanqing. All rights reserved.
//

#import "ViewController.h"

@interface ViewController () <NSURLSessionDataDelegate>

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSString *urlString=@"xxxxz/videos/xxx.mp4";
    

    NSURLSession *session=[NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc]init]];
    
    NSURLSessionDataTask *task=[session dataTaskWithURL:[NSURL URLWithString:urlString]];
    
    [task resume];
    
}

-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler{
    
    NSLog(@"接收到服务器响应");
    
    //设置了该属性,才可以接受到服务端端数据
    completionHandler(NSURLSessionResponseAllow);
    
}

-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data{
    
}

-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{
    
    NSLog(@"下载出错了");
    
}


- (void)didReceiveMemoryWarning {
    
    [super didReceiveMemoryWarning];
}

@end

你可能感兴趣的:(NSURLSession代理实现一个下载)