NSURLSession的基本用法

- (NSURLSession *)session {
    if (_session == nil) {
        NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
        _session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
    }
    return _session;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    NSURL *url = [NSURL URLWithString:@"http://localhost/123.mp4"];
    NSURLSessionDataTask *task = [self.session dataTaskWithURL:url];
    [task resume];
}

#pragma mark - 
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
    NSLog(@"完成-->%lu",(unsigned long)task.taskIdentifier);
}

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler {
    NSLog(@"%@", response);
    
    // 对响应做出的处置
    /**
     NSURLSessionResponseCancel = 0,            取消
     NSURLSessionResponseAllow = 1,             允许
     NSURLSessionResponseBecomeDownload = 2,    变成下载任务
     */
    completionHandler(NSURLSessionResponseAllow);
}

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
    NSLog(@"%tu", data.length);
}
NSURLSession的基本用法_第1张图片
NSURLSession .png

你可能感兴趣的:(NSURLSession的基本用法)