UI控件 NSURLSession相关代理方法

viewCOntroller.m文件实现:

#import "ViewController.h"

@interface ViewController ()<NSURLSessionDataDelegate>

@property (nonatomic, strong) NSMutableData * resultData;

@end

@implementation ViewController


//**********确保透明传输的安全性

//要初始化数据
- (NSMutableData *)resultData
{
    if ( _resultData == nil ){
        _resultData = [NSMutableData data];
    }
    return _resultData;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    //先照上一节在写一遍创建代码
    //注意 禁用其ATS 特性
    NSURL * url = [NSURL URLWithString:@""];
    
    NSURLRequest * request = [NSURLRequest requestWithURL:url];
    
    NSURLSession * session = [NSURLSession sharedSession];
    
    NSURLSessionDataTask * dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    }];
    
    
    
    [dataTask resume];
    
    [self delete];
    
}

//实现代理方法
//代理方法一大堆 只用NSURLSessionDataDelegate

- (void)delete{
    //先照上一节在写一遍创建代码
    //注意 禁用其ATS 特性
    NSURL * url = [NSURL URLWithString:@""];
    
    NSURLRequest * request = [NSURLRequest requestWithURL:url];
    
    //需要自定义会话对象来设置代理
    //NSURLSession * session = [NSURLSession sharedSession];
    
    //用该方法创建 参数1:配置信息(设置请求,功能类似于NSURLRequest)
    //NSURLSessionConfiguration defaultSessionConfiguration:默认配置信息
    //参数2 设置代理 参数3:代理队列-线程-决定代理方法在哪个线程中调用
    //[NSOperationQueue mainQueue] 主线程
    //[[NSOperationQueue alloc] init] 子线程
    //传nil 则默认 子线程中执行
    
    //此为设置代理
    NSURLSession * session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    
    //设置代理 不要设置dataTask代理 设置session代理
    //session.delegate = self; 这样设置会报错
    
//    NSURLSessionDataTask * dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//        NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
//    }];
    
    //根据会话创建任务
    NSURLSessionDataTask * dataTask = [session dataTaskWithRequest:request];
    
    
    
    
    
    
    [dataTask resume];
}

//常用代理方法
//代理方法1:接收到服务器响应的时候会调用
 - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
    //设置线程的参数 [NSThread currentThread]
    NSLog(@"didReceiveResponse--%@",[NSThread currentThread]);
    //需要通过调用completionHandler 告诉系统如何处理服务器返回的数据
    if ( self.resultData == nil ){
        self.resultData = [[NSMutableData alloc] init];
    }//如果之前有数据 那么就要把之前的数据清空 然后显示新的数据
    else{
        self.resultData.length = 0;
    }
    completionHandler(NSURLSessionResponseAllow); //告诉服务器接收返回的数据
}


//代理方法2:接收到服务器返回数据的时候调用 该方法可能会被调用多次
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
    NSLog(@"didReceiveData");
    
    //拼接服务器返回的数据
    [self.resultData appendData:data];
}

//代理方法3:请求完成或者是失败的时候调用 通过判断error是否有值 来判断是否请求失败
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
    NSLog(@"didCompleteWithError");
    if ( error == nil ){
    NSLog(@"%@",[[NSString alloc] initWithData:self.resultData encoding:NSUTF8StringEncoding]);
        
    //或者
        //NSJSONReadingMutableContainers:判断是否是字典 或数组
        id objc = [NSJSONSerialization JSONObjectWithData:self.resultData options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"-----%@",objc);
    }
}


//- (void)viewDidLoad {
//    [super viewDidLoad];
//    // Do any additional setup after loading the view, typically from a nib.
//}
//
//
//- (void)didReceiveMemoryWarning {
//    [super didReceiveMemoryWarning];
//    // Dispose of any resources that can be recreated.
//}


@end

猜你喜欢

转载自blog.csdn.net/teropk/article/details/81810991