[IOS] - 网络模块 NSURLConnection、NSURLSession、AFNetworking

NSURLConnection 是 苹果官网库中自带的简单网络请求的一个类,主要提供了使用URL创建同步和异步请求的方法,NSURLConnection-API

简单介绍一下NSURLConnection 的使用方法

使用NSURLConnection 发送GET同步请求
// 1. 创建URL对象
NSURL *url = [NSURL URLWithString:@"http://mock.allhome.com.cn/mock/5cf76e16de83be001011e63c/0605/header"];
// 2. 创建请求对象
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 3. 发送同步请求 参数1:请求对象 参数2:响应头信息 参数3:错误信息
NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
// 打印返回数据
NSLog(@"data:%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);    

上边的运行结果输出如下图
1257430-20190630200745403-1069321039.png

使用NSURLConnection 发送GET异步请求
// 1. 创建URL对象
NSURL *url = [NSURL URLWithString:@"http://mock.allhome.com.cn/mock/5cf76e16de83be001011e63c/0605/header"];
// 2. 创建请求对象
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 3. 发送异步请求 参数1:请求对象 参数2:请求执行的任务队列 参数3:回调方法
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
   // 参数1: 响应头信息,参数2:响应体信息  参数3:错误信息
   NSLog(@"响应头:%@", response);
   NSLog(@"响应体:%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
   NSLog(@"错误信息:%@", connectionError);
}];

上边的运行结果输出如下图
1257430-20190630201427206-1873613263.png

使用NSURLConnection 发送POST请求
// 1. 创建URL对象
NSURL* postUrl = [NSURL URLWithString:@"http://mock.allhome.com.cn/mock/5cf76e16de83be001011e63c/0605/list"];
// 2. 创建请求对象
NSMutableURLRequest* postRequest = [NSMutableURLRequest requestWithURL:postUrl];
[postRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[postRequest setHTTPMethod:@"POST"];
NSDictionary* body = @{@"page":@"1",@"size":@"10"};
postRequest.HTTPBody = [NSJSONSerialization dataWithJSONObject:body options:NSJSONWritingPrettyPrinted error:nil];
// 6.3 发送POST请求
NSData* data = [NSURLConnection sendSynchronousRequest:postRequest returningResponse:nil error:nil];
NSLog(@"data = %@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);

上边的运行结果输出如下图
1257430-20190630202020788-1485089654.png

一般情况下NSURLConnection就像上边这些使用方式(还有一种通过代理处理数据的方式),但是在项目中一般不会直接使用NSURLConnection作为网络请求的选择

NSURLSession 也是苹果官方提供用类,包含了下载数据和上传数据并可以在程序未运行是执行后台下载的任务。NSURLSessiion-Api

简单介绍一下NSURLSession 的使用方法

使用NSURLSession 发送GET同步请求
// 1. 创建URL对象
NSURL *url = [NSURL URLWithString:@"http://mock.allhome.com.cn/mock/5cf76e16de83be001011e63c/0605/header"];
// 2. 创建会话对象
NSURLSession *session = [NSURLSession sharedSession];
// 3. 创建数据请求任务
NSURLSessionDataTask* task = [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    NSLog(@"data:%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
}];
// 4. 执行任务
[task resume];

上面代码执行后输出如下:
1257430-20190630204201602-701720401.png

发送POST请求其实也是差不多通过设置请求对象的相关属性,然后使用NSURLSession用请求对象去创建任务,然后获得任务对象调用其执行方法,还有一些上传、下载的方法看看API试一试就行了,下边主要介绍一下AFNetworking

AFNetworking 是 IOS 网络三方库,主要是对NSURLConnection和NSURLSession的二次封装,是项目中使用最频繁的模块

AFNetworking 主要包含几个主要模块:
  1. AFURLRequestSerialization
  2. AFURLResponseSerialization
  3. AFURLSessionManager
  4. AFHTTPSessionManager

下面简单介绍一下他们的使用方法

使用AFHTTPSessionManager 发送GET请求
// 1. 创建AFHTTPSessionManager 对象
AFHTTPSessionManager* manager = [AFHTTPSessionManager manager];
// 2. 发送GET请求
[manager GET:@"http://mock.allhome.com.cn/mock/5cf76e16de83be001011e63c/0605/header" parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
    NSLog(@"下载进度:任务总量:%lld 已完成任务:%lld",downloadProgress.totalUnitCount, downloadProgress.completedUnitCount);
} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    NSLog(@"返回数据: %@", responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    NSLog(@"发生错误了: %@", error);
}];

执行后返回信息如下图所示
1257430-20190630210636262-1608525324.png

使用AFHTTPSessionManager 发送POST请求
// 1. 创建会话配置对象
NSURLSessionConfiguration* config = [NSURLSessionConfiguration defaultSessionConfiguration];
// 2. 创建会话管理对象
AFHTTPSessionManager* manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:config];
NSDictionary* params = @{@"page":@1,@"size":@10};
// 3. 创建POST请求任务
NSURLSessionDataTask* task = [manager POST:@"http://mock.allhome.com.cn/mock/5cf76e16de83be001011e63c/0605/list" parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
    NSLog(@"任务总量:%lld 已完成任务:%lld",uploadProgress.totalUnitCount, uploadProgress.completedUnitCount);
} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    NSLog(@"返回数据:%@",responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    NSLog(@"返回错误:%@", error);
}];
// 4. 开启任务
[task resume];

执行后返回信息如下图所示
1257430-20190630210021640-768298607.png

AFURLSessionManager 下载文件
// 创建会话配置对象
NSURLSessionConfiguration* config = [NSURLSessionConfiguration defaultSessionConfiguration];
// 创建会话代理
AFURLSessionManager* manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:config];
// 下载URL
NSURL* url = [NSURL URLWithString:@"https://images.cnitblog.com/blog/497279/201311/29223500-176eb123446f463d8b118dd93e0e7d9b.png"];
// 创建url请求对象
NSURLRequest* request = [NSURLRequest requestWithURL:url];
// 创建下载任务
NSURLSessionDownloadTask* task = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
    NSLog(@"%@ %@", targetPath, response.suggestedFilename);
    NSString *cacheDir = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
    NSString *path = [cacheDir stringByAppendingPathComponent:response.suggestedFilename];// URLWithString返回的是网络的URL,如果使用本地URL,需要注意
    NSURL *fileURL1 = [NSURL URLWithString:path];
    NSURL *fileURL = [NSURL fileURLWithPath:path];
    NSLog(@"== %@ |||| %@", fileURL1, fileURL);
    return fileURL;
} completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
    NSLog(@"%@ %@", filePath, error);
}];
// 开启下载任务
[task resume];

执行后效果如下图
1257430-20190630210304397-687945218.png

AFURLSessionManager 上传文件
// sessionConfig 对象
NSURLSessionConfiguration* config = [NSURLSessionConfiguration defaultSessionConfiguration];
// 1. 创建AFURLSessionManager对象
AFURLSessionManager* manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:config];
// 创建请求对象
NSURL* url = [NSURL URLWithString:@"http://mock.allhome.com.cn/mock/5cf76e16de83be001011e63c/0605"];
NSURLRequest* request = [[NSURLRequest alloc] initWithURL:url];
// 本地图片地址
NSURL* fileURL = [NSURL fileURLWithPath: @"/Users/wrp/Desktop/logo.png"];
// 2. 创建上传文件任务
NSURLSessionUploadTask* task = [manager uploadTaskWithRequest:request fromFile:fileURL progress:^(NSProgress * _Nonnull uploadProgress) {
    NSLog(@"上传进度:%lld, %lld", uploadProgress.totalUnitCount, uploadProgress.completedUnitCount);
} completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
    NSLog(@"响应数据:%@", responseObject);
    NSLog(@"错误消息:%@", error);
}];
// 3. 执行上传任务
[task resume];

执行后显示如下
1257430-20190630210845526-1997383733.png

转载于:https://www.cnblogs.com/wrup/p/11110952.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值