NSURLSession的知识小记

1.NSURLSession的使用流程

使用NSRULSession对象创建Task, 然后执行Task

2.获取NSURLSession

1)获得共享的Session
+ (NSURLSession *)sharedSession;
(2)自定义Session

3.常见的方法

- (void)suspend; // 暂停
- (void)resume;  //恢复
- (void)cancel;    //取消

4.NSURLSession中post请求的代码示例:

    //1.确定请求路径
    NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login"];
    //2.创建可变的请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //3.修改请求头
    request.HTTPMethod = @"POST";
    //4.设置参数
    request.HTTPBody = [@"username=520it&pwd=520it&type=JSON" dataUsingEncoding:NSUTF8StringEncoding];
    //5.创建会话对象
    NSURLSession *session = [NSURLSession sharedSession];
    //6.创建任务请求
    //注意:completionHandler默认在子线程中调用
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        //8. 解析服务器返回的数据
        NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    }];
    //7.执行请求
    [dataTask resume];

注意:NSURLSession中的completionHandle 的block是默认在子线程中调用的

原文地址:https://www.cnblogs.com/lyz0925/p/11574003.html