最近一直在研究iOS网络开发,对NSURLSession套件进行了深入研究,作为iOS开发者,熟悉苹果的原生技术,可以在不需要第三方框架的情况下进行网络开发,也更有利于从底层了解iOS网络请求的原理,不过为了便捷开发,我们可能使用点第三方的框架的机会会更多,这就不得不提AFNetworking了,我将通过本文总结AFNetworking2.0的使用。

AFNetworking的版本和要求

我们先来了解AFNetworking的各个版本:

AFNetworking的结构

我们再通过一张表来清晰地介绍AFNetworking 2.0包含的类,以及它的结构。

AFNetworking 2.0类结构

NSURLConnection

AFURLConnectionOperation

NSOperation子类,实现NSURLConnection代理方法

AFHTTPRequestOperation

AFURLConnectionOperation子类,用于http和https请求,封装了状态码和content type

AFHTTPRequestOperationManager

封装了常见的http网络通信,包括request请求的建立、response响应的数据格式序列化、网络状态监控、安全以及请求的管理等工作。

NSURLSession

AFURLSessionManager

对NSURLSession网络请求技术的封装。它基于NSURLSessionConfiguration对象来创建和管理NSURLSession对象,并且遵守了NSURLSessionTaskDelegate、NSURLSessionDataDelegate、NSURLSessionDownloadDelegate、NSURLSessionDelegate。

AFHTTPSessionManager

AFURLSessionManager的子类,主要提供了了http请求的有关方法

Serialization

序列化

AFHTTPRequestSerializer

AFJSONRequestSerializer

AFPropertyListRequestSerializer

AFHTTPResponseSerializer

AFJSONResponseSerializer

AFXMLParserResponseSerializer

AFXMLDocumentResponseSerializer

AFPropertyListResponseSerializer

AFImageResponseSerializer

AFCompoundResponseSerializer

监控网络

AFNetworkReachabilityManager

AFNetworkReachabilityManager监测域名以及IP地址的畅通性,对于WWAN以及WiFi的网络接口都管用。

附加功能

AFSecurityPolicy

AFNetworkReachabilityManager

AFNetworking各大类介绍

一、AFHTTPRequestOperationManager

AFHTTPRequestOperationManager封装了常见的http网络通信,包括request请求的建立、response响应的数据格式序列化、网络状态监控、安全以及请求的管理等工作。

1.get请求

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:@"http://example.com/resources.json" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

2.post请求

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = @{@"foo": @"bar"};
[manager POST:@"http://example.com/resources.json" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

3.更复杂的post请求

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = @{@"foo": @"bar"};
NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];
[manager POST:@"http://example.com/resources.json" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    [formData appendPartWithFileURL:filePath name:@"image" error:nil];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"Success: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

二、AFURLSessionManager

AFURLSessionManager主要是对NSURLSession网络请求技术的封装。它基于NSURLSessionConfiguration对象来创建和管理NSURLSession对象,并且遵守了NSURLSessionTaskDelegate、NSURLSessionDataDelegate、NSURLSessionDownloadDelegate、NSURLSessionDelegate。

1.创建下载任务

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

NSURL *URL = [NSURL URLWithString:@"http://example.com/download.zip"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];

NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
    NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
    return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
    NSLog(@"File downloaded to: %@", filePath);
}];
[downloadTask resume];

2.创建上传任务

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];

NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
    if (error) {
        NSLog(@"Error: %@", error);
    } else {
        NSLog(@"Success: %@ %@", response, responseObject);
    }
}];
[uploadTask resume];

3.创建包含进度显示的复杂的上传任务

NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileURL:[NSURL fileURLWithPath:@"file://path/to/image.jpg"] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil];
    } error:nil];

AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSProgress *progress = nil;

NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
    if (error) {
        NSLog(@"Error: %@", error);
    } else {
        NSLog(@"%@ %@", response, responseObject);
    }
}];

[uploadTask resume];

4.创建数据任务

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];

NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
    if (error) {
        NSLog(@"Error: %@", error);
    } else {
        NSLog(@"%@ %@", response, responseObject);
    }
}];
[dataTask resume];

三、AFNetworkReachabilityManager

AFNetworkReachabilityManager监测域名以及IP地址的畅通性,对于WWAN以及WiFi的网络接口都管用。

1.单例形式检测网络畅通性

[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
    NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));
}];

2.用基本的URL管理HTTP

NSURL *baseURL = [NSURL URLWithString:@"http://example.com/"];
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:baseURL];

NSOperationQueue *operationQueue = manager.operationQueue;
[manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
  switch (status) {
    case AFNetworkReachabilityStatusReachableViaWWAN:
    case AFNetworkReachabilityStatusReachableViaWiFi:
      [operationQueue setSuspended:NO];
      break;
    case AFNetworkReachabilityStatusNotReachable:
    default:
      [operationQueue setSuspended:YES];
      break;
  }
}];

四、AFHTTPRequestOperation

  AFHTTPRequestOperation 继承自 AFURLConnectionOperation,使用HTTP以及HTTPS协议来处理网络请求。它封装成了一个可以令人接受的代码形式。当然AFHTTPRequestOperationManager 目前是最好的用来处理网络请求的方式,但AFHTTPRequestOperation 也有它自己的用武之地。

1.AFHTTPRequestOperation发送get请求

NSURL *URL = [NSURL URLWithString:@"http://example.com/resources/123.json"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
op.responseSerializer = [AFJSONResponseSerializer serializer];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];
[[NSOperationQueue mainQueue] addOperation:op];

2.多操作一起进行

NSMutableArray *mutableOperations = [NSMutableArray array];
for (NSURL *fileURL in filesToUpload) {
    NSURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileURL:fileURL name:@"images[]" error:nil];
    }];

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

    [mutableOperations addObject:operation];
}

NSArray *operations = [AFURLConnectionOperation batchOfRequestOperations:@[...] progressBlock:^(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations) {
    NSLog(@"%lu of %lu complete", numberOfFinishedOperations, totalNumberOfOperations);
} completionBlock:^(NSArray *operations) {
    NSLog(@"All operations in batch complete");
}];
[[NSOperationQueue mainQueue] addOperations:operations waitUntilFinished:NO];

AFNetworking3.0概述的更多相关文章

  1. 基于AFNetworking3.0网络封装

    概述 对于开发人员来说,学习网络层知识是必备的,任何一款App的开发,都需要到网络请求接口.很多朋友都还在使用原生的NSURLConnection一行一行地写,代码到处是,这样维护起来更困难了. 对于 ...

  2. IOS 网络浅析-(十一 三方 AFNetworking3.0简介)

    AFNetworking3.0是目前最新的版本,本来打算介绍一下2.6,但是想想2.6名不久矣,就决定不介绍了,有兴趣的小伙伴可以上网查一查.下面我就开始进入正题了. 目前使用人数最多的第三方网络库, ...

  3. iOS 适配https(AFNetworking3.0为例)

    众所周知,苹果有言,从2017年开始,将屏蔽http的资源,强推https楼主正好近日将http转为https,给还没动手的朋友分享一二 1.准备证书 首先找后台要一个证书(SSL证书,一般你跟后台说 ...

  4. 网络婚礼之AFNetWorking3.0

    目前使用人数最多的第三方网络库,没有之一.从开始的NSURLConnection到现在的NSURLSession,它都一直保持着与苹果的步调一致,而由它也衍生出大量的相关第三方网络功能库,不仅仅因为他 ...

  5. iOS- 利用AFNetworking3.0+(最新AFN) - 实现文件断点下载

    官方建议AFN的使用方法   0.导入框架准备工作 •1. 将AFNetworking3.0+框架程序拖拽进项目   •2. 或使用Cocopod 导入AFNetworking3.0+   •3.   ...

  6. iOS开发--基于AFNetWorking3.0的图片缓存分析

    图片在APP中占有重要的角色,对图片做好缓存是重要的一项工作.[TOC] 理论 不喜欢理论的可以直接跳到下面的Demo实践部分 缓存介绍 缓存按照保存位置可以分为两类:内存缓存.硬盘缓存(FMDB.C ...

  7. AFNetworking3.0+MBProgressHUD二次封装,一句话搞定网络提示

    对AFNetworking3.0+MBProgressHUD的二次封装,使用更方便,适用性非常强: 一句话搞定网络提示: 再也不用担心网络库更新后,工程要修改很多地方了!网络库更新了只需要更新这个封装 ...

  8. iOS_SN_基于AFNetworking3.0网络封装

    转发文章,原地址:http://www.henishuo.com/base-on-afnetworking3-0-wrapper/?utm_source=tuicool&utm_medium= ...

  9. AFNetworking3.0的基本使用方法

    前一段时间在做项目的时候发现AFNetworking3.0已经被大众所接受,所以以后肯定会有很多程序猿朋友必须了解和转移至3.0了,这是我这段时间使用和学习总结出来的一些常用的知识点,希望对大家有用. ...

随机推荐

  1. css-高度自适应的问题(body高度问题)

    css-高度自适应的问题 对象height:100%并不能直接产生效果,是因为跟其父对象有关. #center{ height:100%; } 上面的css样式是无效的,不会产生任何效果. 需要改写: ...

  2. drush cc all 报错

    请看好 指明了Module文件的行数 报错一定要多看看哦.

  3. Laravel 实现定时任务

    运行命令schedule run 时laravel会去App\console\kernel.php文件中查找schedule方法,有没有要执行的定时命令 实现流程:首先可以自定义命令并注册命令(参考上 ...

  4. bootstrap的警告框

    .alert 基础警告框 .alert-danger  红色警告框 .alert-dismissable  修饰警告框 alert-dismiss="alert" 触发警告框 // ...

  5. ScrollView嵌套StackView提示需要宽度和高度限制

    场景: 在一个xib的view中,添加一个ScrollView,再在这个ScrollView中添加一个StackView,StackView中不加控件(用代码动态加). 问题: 提示ScrollVie ...

  6. Struts2配置拦截器,struts2加载常量时的搜索顺序

    1:struts2加载常量时的搜索顺序 1.Struts-default.xml 2.Struts-plugin.xml 3.Struts.xml 4.Struts-properties(自己创建的) ...

  7. plot a critical difference diagram , MATLAB code

    plot a critical difference diagram , MATLAB code 建立criticaldifference函数 function cd = criticaldiffer ...

  8. BZOJ2494 Triangles and Quadrangle

    一道非常"简单"的计算几何题... 题意:给你两个三角形和一个四边形,问你能否用这两个三角形拼成这个四边形 首先...四边形可能是凹四边形...需要判断一下...这个比较简单直接分 ...

  9. svn 备份后双机同步热备失效,提示 W200007 target server does not support atomic revision property edits svynsync:E170009

    svn 备份后双机同步热备失效,提示 W200007 target server does not support atomic revision property edits; consider u ...

  10. Linux下配置用msmtp和mutt发邮件

    Linux下可以直接用mail命令发送邮件,但是发件人是user@servername,如果机器没有外网的dns,其他人就无法回复.此时,有一个可以使用网络免费邮箱服务的邮件发送程序就比较重要了.ms ...