iOS 多线程编程<十七、NSURLSession的基本用法>

苹果推出NSURLSession是为了代替NSURLConnection

看一下NSURLSession的基本用法:代码如下

<span style="font-size:10px;">//
//  ViewController.m
//  NSURLSession
//
//  Created by fe on 2016/11/7.
//  Copyright © 2016年 fe. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()<NSURLSessionDataDelegate>

@end

@implementation ViewController

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self sessionDelegate];
}

- (void)get1
{
    //1:创建URLSession
    NSURLSession *session = [NSURLSession sharedSession];
    
    //2:根据会话对象来创建task
    /*
     第一个参数:请求对象
     第二个参数:data:响应体
     response:响应头
     error:错误信息
     */
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.baidu.com"]];
    NSURLSessionDataTask *dataTask  =  [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSLog(@"%@---%@",error,[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
        
    }];
    
    [dataTask resume];
}

- (void)get2
{
    //1:创建URLSession
    NSURLSession *session = [NSURLSession sharedSession];
    
    //2:根据会话对象来创建task
    /*
     第一个参数:请求对象
     第二个参数:data:响应体
     response:响应头
     error:错误信息
     */
    NSURL *url = [NSURL URLWithString:@"https://www.baidu.com"];
    NSURLSessionDataTask *dataTask  =  [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
    }];
                                        
    [dataTask resume];
}

- (void)sessionDelegate
{
    //1:创建session,并设置代理
    /*
     第一个参数:配置信息
     第三个参数:控制代理方法在哪个线程调用
     */
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
    //2:创建task
    NSURLSessionTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString:@"https://www.baidu.com"]];
    //3:启动
    [dataTask resume];
}

#pragma mark - NSURLSessionDataDelegate -
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
didReceiveResponse:(NSURLResponse *)response
 completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler;
{
    /*
     NSURLSessionResponseCancel = 0   取消(默认)
     NSURLSessionResponseAllow = 1    允许接受数据
     NSURLSessionResponseBecomeDownload = 2
     NSURLSessionResponseBecomeStream
     */
    //请求策略,如果不设置请求策略,默认为NSURLSessionResponseCancel,则接收不到数据
    completionHandler(NSURLSessionResponseAllow);
}
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
    didReceiveData:(NSData *)data;
{
    
}

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
    
}
@end</span>


你可能感兴趣的:(iOS 多线程编程<十七、NSURLSession的基本用法>)