iOS 第三方框架- AFNetworking的基本使用
AFNetworking(发送网络请求)是目前Github里面最流行的OC第三方框架,这个框架十分强大,几乎封装了所有的有关网络的功能;
早期的AFN底层使用NSURLConnectionOperation实现的,iOS6.0以后苹果推出NSURLSession,后来逐步取代NSURLConnectionOperation.
目前的AFN版本已经完全摒弃了NSURLConnectionOperation,底层全部由NSURLSession来实现.
下面列出AFN框架的功能结构:
- NSURLSession
+ AFURLSessionManager
+ AFHTTPSessionManager(封装了常用的 HTTP 方法)
* GET
* POST
* UIKit + AFNetworking 分类
* NSProgress :利用KVO
- 半自动的序列化&反序列化的功能
+ AFURLRequestSerialization :请求的数据格式/默认是二进制的
+ AFURLResponseSerialization :响应的数据格式/默认是JSON格式
- 附加功能
+ 安全策略
* HTTPS
* AFSecurityPolicy
+ 网络检测
* 对苹果的网络连接检测做了一个封装
* AFNetworkReachabilityManager
AFNetworking下载地址:
https://github.com/AFNetworking/AFNetworking
CocoaPods引入方式:
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, "7.0"
target:testAFN do
pod 'AFNetworking','~> 3.1.0'
end
使用前请先导入AFN框架文件,并导入头文件
#import "AFNetworking.h"
- (void)getAFN {
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
NSString *url = @"http://apis.juhe.cn/ip/ip2addr?ip=www.juhe.cn";
[manager GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
// 请求进度
}
success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"请求成功:%@",responseObject);
}
failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"请求失败:%@",error);
}];
}
- (void)postAFN {
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer]; // 请求JSON格式
manager.responseSerializer = [AFJSONResponseSerializer serializer]; // 响应JSON格式
//设置请求头
[manager.requestSerializer setValue:@"application/json;UTF-8" forHTTPHeaderField:@"Content-Type"];
NSString *url = @"http://xxx/app/user/login";
//{"mobile": "18672788083", "password": "password", "DToken": "537e8678186"}
NSDictionary *parameters = @{@"mobile":@"18672788083",
@"password": @"password",
@"DToken": @"537e8678186"};
[manager POST:url parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"请求成功:%@",responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"请求失败:%@",error);
}];
}
- (void)downLoad{
//1.创建管理者对象
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//2.确定请求的URL地址
NSURL *url = [NSURL URLWithString:@""];
//3.创建请求对象
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//下载任务
NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
//打印下下载进度
WKNSLog(@"%lf",1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);
} destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
//下载地址
WKNSLog(@"默认下载地址:%@",targetPath);
//设置下载路径,通过沙盒获取缓存地址,最后返回NSURL对象
NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
return [NSURL URLWithString:filePath];
} completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
//下载完成调用的方法
WKNSLog(@"下载完成:");
WKNSLog(@"%@--%@",response,filePath);
}];
//开始启动任务
[task resume];
}
/**
* AFN 3.0 上传
* 有两种方式
* upLoad1 和 upLoad2
*/
//第一种方法是通过工程中的文件进行上传
- (void)upLoad1{
//1。创建管理者对象
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//2.上传文件
NSDictionary *dict = @{@"username":@"1234"};
NSString *urlString = @"22222";
[manager POST:urlString parameters:dict constructingBodyWithBlock:^(id _Nonnull formData) {
//上传文件参数
UIImage *iamge = [UIImage imageNamed:@"123.png"];
NSData *data = UIImagePNGRepresentation(iamge);
//这个就是参数
[formData appendPartWithFileData:data name:@"file" fileName:@"123.png" mimeType:@"image/png"];
} progress:^(NSProgress * _Nonnull uploadProgress) {
//打印下上传进度
WKNSLog(@"%lf",1.0 *uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
//请求成功
WKNSLog(@"请求成功:%@",responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//请求失败
WKNSLog(@"请求失败:%@",error);
}];
}
//第二种是通过URL来获取路径,进入沙盒或者系统相册等等
- (void)upLoda2{
//1.创建管理者对象
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//2.上传文件
NSDictionary *dict = @{@"username":@"1234"};
NSString *urlString = @"22222";
[manager POST:urlString parameters:dict constructingBodyWithBlock:^(id _Nonnull formData) {
[formData appendPartWithFileURL:[NSURL fileURLWithPath:@"文件地址"] name:@"file" fileName:@"1234.png" mimeType:@"application/octet-stream" error:nil];
} progress:^(NSProgress * _Nonnull uploadProgress) {
//打印下上传进度
WKNSLog(@"%lf",1.0 *uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
//请求成功
WKNSLog(@"请求成功:%@",responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//请求失败
WKNSLog(@"请求失败:%@",error);
}];
}
- (void)AFNetworkStatus{
//1.创建网络监测者
AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
/*枚举里面四个状态 分别对应 未知 无网络 数据 WiFi
typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) {
AFNetworkReachabilityStatusUnknown = -1, 未知
AFNetworkReachabilityStatusNotReachable = 0, 无网络
AFNetworkReachabilityStatusReachableViaWWAN = 1, 蜂窝数据网络
AFNetworkReachabilityStatusReachableViaWiFi = 2, WiFi
};
*/
[manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
//这里是监测到网络改变的block 可以写成switch方便
//在里面可以随便写事件
switch (status) {
case AFNetworkReachabilityStatusUnknown:
WKNSLog(@"未知网络状态");
break;
case AFNetworkReachabilityStatusNotReachable:
WKNSLog(@"无网络");
break;
case AFNetworkReachabilityStatusReachableViaWWAN:
WKNSLog(@"蜂窝数据网");
break;
case AFNetworkReachabilityStatusReachableViaWiFi:
WKNSLog(@"WiFi网络");
break;
default:
break;
}
}] ;
}