iOS学习使用NSURLSession

老的人知道NSURLconnection

年轻的人知道NSURLsession

帅的人在这给大家讲解NSURLsession

本文给大家讲一个NSURLSession的用法,并且结合现在最新版的AFNetworking(3.1.0)来实现同样的功能,将会带来全新的体验哦:

  • NSURLSession的基本讲解
  • 实现GET,POST,下载图片等功能
  • 用最新版的AFN(3.1.0)来实现同样的功能

NSURLSession的基本讲解

在开发网络相关的应用,就必然需要使用到HTTP请求来发送或者接收数据。最主要的就是使用GET方法或者POST方法。本文将详细介绍NSURLSession在HTTP请求在iOS开发中的编程实现

首先要明白NSURLSession有那几部分组成

在以NSURLSession为主流的网络请求的时候,就要先弄清楚他们的关系,
这里写图片描述

由上图可看出,整个NSURLSession就想一个帝王,如秦始皇一样叼的帝王。暂且我们把NSURLSession当一个秦王,手下就要有治理军队的大将军和梳理政务的丞相两大马车。这里的NSURLSessionConfiguration就好比是一个上将军。上将军手底下有多个大军的前将军这里就好比就是无数个NSURLSessionTask,这里就是手底下的各种兵种了。

NSURLSessionTask:就是数据操作的小兵:
NSURLSessionDataTask:普通的数据传输,拿到的数据是NSData格式,你可以根据数据原本的格式进行相应的转换。
NSURLSessionUploadTask:用于上传
NSURLSessionDownloadTask:用于下载,这个类与其它两个类有点不一样,这个类下载到的东西是直接写在一个临时文件中的,下载好之后它会给你一个临时文件的指针,然后自己手动保存。

废话不多看 对比代码的实现

使用 GET 请求
/**
 *  基本的网络请求
 */
-(void)basicURLRequest {
    
    NSString *url = @"http://open.qyer.com/qyer/bbs/forum_thread_list?client_id=qyer_android&client_secret=9fcaae8aefc4f9ac4915&forum_id=1&type=1&count=10&page=1&delcache=0";
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
    
    NSURLSessionConfiguration * configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession * session = [NSURLSession sessionWithConfiguration:configuration];
    // 基本网络请求
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (!error) {
            
            NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
            
            if (httpResponse.statusCode == 200) {
                
                NSString *string = [[NSString alloc] initWithData:data encoding:NSStringEncodingConversionAllowLossy];
                NSLog(@"%@",string);
            }
        }
    }];
    
    [dataTask resume];
}
// ————————————————看一下AFN的网络请求
/**
 *  基于AFN的网络POST请求
 */
-(void)AFNBasicRequesthttpBody {
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

    NSString *url = @"http://open.qyer.com/qyer/bbs/forum_thread_list";

    NSDictionary * dict = @{@"client_id":@"qyer_android",@"client_secret":@"9fcaae8aefc4f9ac4915",@"forum_id":@"1"};
    // 这里把字典转换成GET请求后的凭接地址
    NSString *URLFellowString = [@"?" stringByAppendingString:[NSString queryStringFromDictionary:dict addingPercentEscapes:YES]];
    NSURL *URL = [NSURL URLWithString:[url stringByAppendingString:URLFellowString]];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
    NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if (error) {
            NSLog(@"-------Error: %@", error);
        } else {
            NSLog(@">>>>>%@", responseObject);
        }
    }];
    
    [dataTask resume];
}

使用 GET 请求
/**
 *  基本的POST请求
 */
-(void)BasicPostRequst {
    //1.创建会话对象
    NSURLSessionConfiguration * configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession * session = [NSURLSession sessionWithConfiguration:configuration];
    //2.根据会话对象创建task
    NSURL *url = [NSURL URLWithString:@"http://icloud.chinacloudapp.cn/icloud/app/v1/user/userlogin.do"];
    //3.创建可变的请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    // 设置向服务器发送json格式数据
    [request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
    //4.修改请求方法为POST
    request.HTTPMethod = @"POST";
    
    NSDictionary *parameters = @{@"phone":@"18790723015",@"pwd":@"123456",@"device_token":@"71c26d22d85686e37658524adc1541ce88bc05c4f0e788b0ffe315e9e3f98378",@"client_type":@1};
    NSError*  error;
    //5.设置请求体
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:&error];
    request.HTTPBody = jsonData;
    
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        //8.解析数据
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
        NSLog(@"%@",dict);
    }];
    
    //7.执行任务
    [dataTask resume];
}

// ___________下面基于AFN的网络POST请求
/**
 *  基于AFN的网络POST请求
 */
-(void)AFNHttpPostRequest {
    NSURLSessionConfiguration * configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager * manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    NSURL *url = [NSURL URLWithString:@"http://icloud.chinacloudapp.cn/icloud/app/v1/user/userlogin.do"];
    
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
    [request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
    [request setHTTPMethod:@"POST"];
    
    NSDictionary *parameters = @{@"phone":@"15010206793",@"pwd":@"123456",@"device_token":@"71c26d22d85686e37658524adc1541ce88bc05c4f0e788b0ffe315e9e3f98378",@"client_type":@1};
    NSError*  error;
    //5.设置请求体
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:&error];
    request.HTTPBody = jsonData;
    
    
    NSURLSessionDataTask * task = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (!error) {
            NSLog(@"---%@",responseObject);
        }
    }];
    [task resume];
}
图片下载
/**
 *  基本下载图片方法
 */
-(void)BaseDownloadImage {
    NSURL * url = [NSURL URLWithString:@"http://image.tianjimedia.com/uploadImages/2011/252/8GO666XNQM49.jpg"];
    NSURLSessionConfiguration * configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession * session = [NSURLSession sessionWithConfiguration:configuration];
    NSURLRequest * request = [NSURLRequest requestWithURL:url];
    // 当statusCode等于200时,表示网络没问题
    NSURLSessionDownloadTask * task = [session downloadTaskWithRequest:request completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (!error) {
            UIImage *imageData = [UIImage imageWithData:[NSData dataWithContentsOfURL:location]];
            dispatch_async(dispatch_get_main_queue(), ^{
                self.imageView.image =  imageData;
            });
        }
    }];
    [task resume];
}


//______________基于AFN的图片下载
/**
 *  基于AFN的网络下载
 */
-(void)AFNDownloadImage {
    NSURLSessionConfiguration * configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager * manager = [[AFURLSessionManager alloc]initWithSessionConfiguration:configuration];
    NSURL * url = [NSURL URLWithString:@"http://image.tianjimedia.com/uploadImages/2011/252/8GO666XNQM49.jpg"];
    NSURLRequest * request = [NSURLRequest requestWithURL:url];
    NSURLSessionDownloadTask * task = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        
        NSURL *downloadURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
        return [downloadURL URLByAppendingPathComponent:[response suggestedFilename]];
        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        if (!error) {
            //此处已经在主线程了
            UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:filePath]];
            self.imageView.image = image;
        }
    }];
    
    [task resume];
}

注释

新的网络用法要使用,不要去使用AFN2.0.x的版本了。小伙看这里 你会发现很多哦

关注洲洲哥的公众号,提高装逼技能就靠他了

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值