AFNetWorking
AFNetWorking一款轻量级网络请求开源框架,适用于iOS, macOS, watchOS, and tvOS,是对网络进行扩展的高性能框架,大大降低了开发工程师处理网络请求的难度。
1.CocoaPods安装
- 用以下命令安装CocoaPods
$ gem install cocoapods
- 整合AFNetworking到项目中,在Podfile文件中:
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
target 'TargetName' do
pod 'AFNetworking', '~> 3.0'
end
- 执行命令行
$ pod install
2.结构
NSURLSession
- AFURLSessionManager
- AFHTTPSessionManager
序列化
- <AFURLRequestSerialization> 请求序列化
- AFHTTPRequestSerializer
- AFJSONRequestSerializer
- AFPropertyListRequestSerializer
- <AFURLResponseSerialization> 响应序列化
- AFHTTPResponseSerializer
- AFJSONResponseSerializer
- AFXMLParserResponseSerializer
- AFXMLDocumentResponseSerializer (Mac OS X)
- AFPropertyListResponseSerializer
- AFImageResponseSerializer
- AFCompoundResponseSerializer
- 其他功能
- AFSecurityPolicy
- AFNetworkReachabilityManager
3.使用AFNetworking
- AFURLSessionManager
AFURLSessionManager创建和管理一个基于特定NSURLSessionConfiguration 的NSURLSession对象,遵循<NSURLSessionTaskDelegate>, <NSURLSessionDataDelegate>, <NSURLSessionDownloadDelegate>, and <NSURLSessionDelegate>协议。
创建一个下载任务
// 1.创建 NSURLSessionConfiguration对象
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
// 2.创建 AFURLSessionManager对象
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
// 3.分别创建 NSURL、NSURLRequest对象
NSURL *URL = [NSURL URLWithString:@"http://example.com/download.zip"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
// 4.创建 NSURLSessionDownloadTask 对象
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);
}];
// 5.开启下载任务
[downloadTask resume];
创建一个上传任务
// 1.创建 NSURLSessionConfiguration 对象
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
// 2.创建 AFURLSessionManager 对象
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
// 3.分别创建 NSURL、NSURLRequest 对象
NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];
// 4.创建 NSURLSessionUploadTask 对象
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);
}
}];
// 5.开启下载任务
[uploadTask resume];
2.AFHTTPSessionManager
AFHTTPSessionManager 是 AFURLSessionManager 的子类对象,它提供了进行 HTTP 请求的便捷方法。当设置好 baseURL (服务器地址)时,就能发起 GET、POST 等请求。
GET 用法
// 1.创建 AFHTTPSessionManager 对象
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
// 2.GET请求
[manager GET:URL parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
//进度
}
success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
// 请求成功
// task:通过task拿到响应头
// responseObject:请求成功返回的响应结果(AFN内部已经把响应体转换为OC对象,通常是字典或数组)
NSLog(@"%@",responseObject);
}
failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
// 请求失败
//这里打印错误信息
NSLog(@"%@",error);
}];
POST 用法
// 1.创建 AFHTTPSessionManager 对象
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
// 2.构建参数
NSMutableDictionary *parameters ;
// 3.POST请求
[manager POST:URL parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
//进度
}
success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
//请求成功
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
// 请求失败
}];
3.AFNetworkReachabilityManager
AFNetworkReachabilityManager
用于监测WWAN 和 WiFi接口网络联通性
//创建网络状态监测管理者,并监听网络状态
[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));
switch (status) {
case AFNetworkReachabilityStatusUnknown: {
NSLog(@"网络异常:未知网络");
break;
}
case AFNetworkReachabilityStatusNotReachable: {
NSLog(@"网络异常:没有网络");
break;
}
case AFNetworkReachabilityStatusReachableViaWWAN: {
NSLog(@"网络状态检测:蜂窝网络");
break;
}
case AFNetworkReachabilityStatusReachableViaWiFi: {
NSLog(@"网络状态检测:WiFi");
break;
}
}
}];
//开启网络检测
[[AFNetworkReachabilityManager sharedManager] startMonitoring];