为大家分享一个IOS处理网络请求,网络上传,网络下载等功能全面的一个第三方框架-AFNetworking,这是一个使用非常方便的网络框架.
最新的版本是基于NSURLSession,原来的NSURLConnectionOperation在此已经移除.
git链接请点击此处
简介
AFNetworking is a delightful networking library for iOS and Mac OS X. It's built on top of the Foundation URL Loading System, extending the powerful high-level networking abstractions built into Cocoa. It has a modular architecture with well-designed, feature-rich APIs that are a joy to use.
Perhaps the most important feature of all, however, is the amazing community of developers who use and contribute to AFNetworking every day. AFNetworking powers some of the most popular and critically-acclaimed apps on the iPhone, iPad, and Mac.
Choose AFNetworking for your next project, or migrate over your existing projects—you'll be happy you did!
翻译:AFNetworking是适用于IOS和MacOS的一个轻量级的网络库.它搭建于URL加载系统的框架之上,扩展了有效的高级网络提取并内置了Cocoa.它提供了设计优秀的模块化体系,方便使用的丰富的API.
最大的特点是每天有惊人数量的社区开发者在为AFNetworking做出贡献. AFNetworking在一些最受欢迎的IPhone,IPad,Mac上的APP都有使用它.
选择AFNetworking在您的下一个项目中,或者移植到你现存的项目上---你将会很乐意于使用它!
大体架构
网络管理类
AFURLSessionManager
AFHTTPSessionManager
请求
AFHTTPRequestSerializer
AFJSONRequestSerializer
AFPropertyListRequestSerializer
响应
AFHTTPResponseSerializer
AFJSONResponseSerializer
AFXMLParserResponseSerializer
AFXMLDocumentResponseSerializer (Mac OS X)
AFPropertyListResponseSerializer
AFImageResponseSerializer
AFCompoundResponseSerializer
AFHTTPSessionManager是AFURLSessionManager的子类,一般推荐使用AFHTTPSessionManager.
在这里我只为大家介绍下封装成工具类的操作,以GET网络请求为例,其他的方法是类似使用的,在项目中大量的使用,这是非常必要的.
创建.h文件
#import <Foundation/Foundation.h>
//因为我是使用pods导入的.所以这里是导入库文件的形式
#import <AFNetworking.h>
@interface NetTools : AFHTTPSessionManager
+(instancetype)shareNetTools;
-(void)GETURLString:(NSString *)URLString andSuccessBlock:(void(^)(id success))successBlock andErrorBlock:(void(^)(NSError *error))errorBlock;
@end
创建.m文件
#import "NetTools.h"
@implementation NetTools
//设计成单例
+(instancetype)shareNetTools
{
static NetTools* instance;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
//设置baseURL.
NSURL *url = [NSURL URLWithString:@"http://c.m.163.com/nc/"];
instance = [[NetTools alloc] initWithBaseURL:url];
//解决反序列问题
instance.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", nil];
});
return instance;
}
//这里是是get请求方法演示,其他的方法类似.
-(void)GETURLString:(NSString *)URLString andSuccessBlock:(void(^)(id success))successBlock andErrorBlock:(void(^)(NSError *error))errorBlock
{
//NSLog(@"当前的请求地址:%@", URLString);
[self GET:URLString parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if (successBlock) {
successBlock(responseObject);
}
NSLog(@"请求成功^");
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if (errorBlock) {
NSLog(@"下载sh%@", error);
errorBlock(error);
}
}];
}
@end