1.為什么要封裝
對(duì)于AFNetworking
的使用,相信大多數(shù)的公司都會(huì)用到,畢竟開源框架,安全高效.為了提高效率和代碼的可維護(hù)性,我們就要二次封裝AFN
.
2,以前遇到問題
一個(gè)老項(xiàng)目,需要進(jìn)行IPV6
的遷移(雖然老版本的AFN
也支持IPV6
),但是方法變了,之前沒有封裝AFN
,項(xiàng)目中用到AFN
請(qǐng)求的地方有很多,接口上千,那么AFN
出現(xiàn)的地方就上千個(gè).更新AFN
后,不支持老方法了,需要用新的方法,則需要替換上千個(gè)方法,這是個(gè)很大的工作量.這時(shí)封裝的好處就體現(xiàn)出來了,只需改一處.
3,如何解決的
如標(biāo)題所示,那就是二次封裝AFNetworking
重點(diǎn)在下面了
AFNetworking的封裝:OC版
首先如下,別問為什么......
cocoapods pod 'AFNetworking'
注意點(diǎn)
- 共享
AFHTTPSessionManager
對(duì)象,而不是每次新建SessionManager
為什么要共享?給你們科普一下:HTTP
協(xié)議是基于TCP
協(xié)議的,所以在每次的HTTP
請(qǐng)求之前,客戶端和服務(wù)器端值戳,都先需要經(jīng)過TCP
連接的三次握手本鸣,即每次請(qǐng)求之前,網(wǎng)絡(luò)的數(shù)據(jù)都已經(jīng)在客戶端和服務(wù)器端之間來回了三次 如下圖:
所以這樣做的目的就是提高請(qǐng)求效率,所以我是這么做的,請(qǐng)看下一步
- ok,坐穩(wěn)開車了
1.創(chuàng)建單例請(qǐng)求對(duì)象
創(chuàng)建一個(gè)類繼承自AFHTTPSessionManager
,如下:
2.封裝方法
- 封裝了幾個(gè)常用的方法:get,post,上傳,下載這幾個(gè)方法,
為什么用類方法?因?yàn)槭褂闷饋砗?jiǎn)單啊!!!
@interface AFNHelper : AFHTTPSessionManager
//單例
+ (AFNHelper *)sharedManager;
/**
* get請(qǐng)求
*
* @param url 接口url
* @param parameters 參數(shù)
* @param success 請(qǐng)求成功的block
* @param failure 請(qǐng)求失敗的block
*/
+ (void)get:(NSString *)url parameter:(id )parameters success:(void(^)(id responseObject))success faliure:(void(^)(id error))failure;
/**
* post請(qǐng)求
*
* @param url 接口url
* @param parameters 參數(shù)
* @param success 請(qǐng)求成功的block
* @param failure 請(qǐng)求失敗的block
*/
+ (void)post:(NSString *)url parameters:(id)parameters success:(void(^)(id responseObject))success faliure:(void(^)(id error))failure;
/**
* post請(qǐng)求 不拼接基地址
*
* @param url 接口url
* @param parameters 參數(shù)
* @param success 請(qǐng)求成功的block
* @param failure 請(qǐng)求失敗的block
*/
+ (void)postNoBaseUrl:(NSString *)url parameters:(id)parameters success:(void(^)(id responseObject))success faliure:(void(^)(id error))failure;
/**
* 文件上傳
*
* @param url 接口url
* @param parameters 參數(shù)
* @param block 圖片data
* @param success 請(qǐng)求成功的block
* @param failure 請(qǐng)求失敗的block
*/
+ (void )post:(NSString *)url parameters:(id)parameters constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block success:(void (^)(id responseObject))success faliure:(void (^)(id error))failure;
/**
* 文件下載
*
* @param request 下載請(qǐng)求
* @param ProgressBlock 下載進(jìn)度block
* @param savePath 儲(chǔ)存路徑
* @param failure 下載失敗block
*/
+ (void)downloadTaskWithUrl:(NSString *)url progress:(void (^)(id downloadProgress))ProgressBlock savePath:(NSString *)savePath completionHandler:(void (^)(NSURLResponse *response ,NSURL *filePath))completion error:(void (^)(id error))failure;
- .m的實(shí)現(xiàn)如下
BaseUrl
是宏
#import "AFNHelper.h"
@implementation AFNHelper
//單例實(shí)現(xiàn)
+ (AFNHelper *)sharedManager {
static AFNHelper *handle = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
handle = [AFNHelper manager];
// 設(shè)置可接受的類型
handle.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"application/json",@"text/json",@"text/javascript",@"text/html",nil];
});
return handle;
}
//get請(qǐng)求
+ (void )get:(NSString *)url parameter:(id)parameters success:(void (^)(id responseObject))success faliure:(void (^)(id error))failure
{
[[AFNHelper sharedManager] GET:[BaseUrl stringByAppendingString:url] parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if(responseObject) {
success(responseObject);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
failure(error);
}];
}
//post請(qǐng)求
+ (void)post:(NSString *)url parameters:(id)parameters success:(void(^)(id responseObject))success faliure:(void(^)(id error))failure {
[[AFNHelper sharedManager] POST:[BaseUrl stringByAppendingString:url] parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if(responseObject) {
success(responseObject);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
failure(error);
}];
}
//文件上傳
+ (void )post:(NSString *)url parameters:(id)parameters constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block success:(void (^)(id responseObject))success faliure:(void (^)(id error))failure{
[[AFNHelper sharedManager] POST:[BaseUrl stringByAppendingString:url] parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
block(formData);
} progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if(responseObject) {
success(responseObject);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
failure(error);
}];
}
//文件下載
+ (void)downloadTaskWithUrl:(NSString *)url progress:(void (^)(id downloadProgress))ProgressBlock savePath:(NSString *)savePath completionHandler:(void (^)(NSURLResponse *response ,NSURL *filePath))completion error:(void (^)(id error))failure{
//創(chuàng)建請(qǐng)求
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[BaseUrl stringByAppendingString:url]]];
//創(chuàng)建任務(wù)
NSURLSessionDownloadTask *download = [[AFNHelper sharedManager] downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
if (downloadProgress) {
ProgressBlock(downloadProgress);
}
} destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
return [NSURL fileURLWithPath:savePath];
}completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
if (!error) {
completion(response,filePath);
}
else {
failure(error);
}
}];
//開啟任務(wù)
[download resume];
}
@end
3.如何使用
這樣的話OC的基本上封裝的實(shí)現(xiàn)就可以了
AFNetworking的封裝:swift版
- swift的基本語(yǔ)法,我就不多說了,能用到這個(gè)的,肯定能看懂語(yǔ)法.....
同上 cocoapods pod 'AFNetworking'
1.創(chuàng)建單例請(qǐng)求對(duì)象
創(chuàng)建一個(gè)類繼承自AFHTTPSessionManager
,如下:
2.具體實(shí)現(xiàn)方法 也是常用的四個(gè)方法
/**
get請(qǐng)求
- parameter urlString: 請(qǐng)求的url
- parameter parameters: 請(qǐng)求的參數(shù)
- parameter success: 請(qǐng)求成功回調(diào)
- parameter failure: 請(qǐng)求失敗回調(diào)
*/
class func get(urlString:String,parameters:AnyObject?,success:((responseObject:AnyObject?) -> Void)?,failure:((error:NSError) -> Void)?) -> Void {
AFNHelper.shareManager.GET(urlString, parameters: parameters, progress: { (progress) in
}, success: { (task, responseObject) in
//如果responseObject不為空時(shí)
if responseObject != nil {
success!(responseObject:responseObject)
}
}) { (task, error) in
failure!(error:error)
}
}
/**
post請(qǐng)求
- parameter urlString: 請(qǐng)求的url
- parameter parameters: 請(qǐng)求的參數(shù)
- parameter success: 請(qǐng)求成功回調(diào)
- parameter failure: 請(qǐng)求失敗回調(diào)
*/
class func post(urlString:String,parameters:AnyObject?,success:((responseObject:AnyObject?) -> Void)?,failure:((error:NSError) -> Void)?) -> Void {
AFNHelper.shareManager.POST(urlString, parameters: parameters, progress: { (progress) in
}, success: { (task, responseObject) in
//如果responseObject不為空時(shí)
if responseObject != nil {
success!(responseObject:responseObject)
}
}) { (task, error) in
failure!(error:error)
}
}
/**
文件上傳
- parameter urlString: 請(qǐng)求的url
- parameter parameters: 請(qǐng)求的參數(shù)
- parameter constructingBodyWithBlock: 文件data
- parameter uploadProgress: 上傳進(jìn)度
- parameter success: 請(qǐng)求成功回調(diào)
- parameter failure: 請(qǐng)求失敗回調(diào)
*/
class func POST(urlString: String, parameters: AnyObject?, constructingBodyWithBlock:((formData:AFMultipartFormData) -> Void)?, uploadProgress: ((progress:NSProgress) -> Void)?, success: ((responseObject:AnyObject?) -> Void)?, failure: ((error: NSError) -> Void)?) -> Void {
AFNHelper.shareManager.POST(urlString, parameters: parameters, constructingBodyWithBlock: { (formData) in
constructingBodyWithBlock!(formData:formData)
}, progress: { (progress) in
uploadProgress!(progress:progress)
}, success: { (task, objc) in
if objc != nil {
success!(responseObject:objc)
}
}) { (task, error) in
failure!(error:error)
}
}
/**
下載文件
- parameter request: 請(qǐng)求的request
- parameter downloadProgressBlock: 下載的進(jìn)度
- parameter savePath: 存儲(chǔ)路徑
- parameter completionHandler: 完成后回調(diào)
*/
class func downloadTaskWithRequest(request: NSURLRequest, downloadProgressBlock: ((downloadProgress :NSProgress) -> Void)?, savePath: String,completionHandler:((response:NSURLResponse, error:NSError?) -> Void)?) -> Void{
//創(chuàng)建下載任務(wù)
let task = AFNHelper.shareManager.downloadTaskWithRequest(request, progress: { (progress) in
downloadProgressBlock!(downloadProgress:progress)
}, destination: { (url, response) -> NSURL in
return NSURL(fileURLWithPath: savePath)
}) { (response, url, error) in
if (error == nil) {
completionHandler!(response:response ,error:error)
}
}
//開啟下載
task.resume()
}
3.如何使用
截個(gè)圖吧 如下:
以上就是swift版本的AFN封裝,看完之后覺得很簡(jiǎn)單吧
4.總結(jié)
以上只是我自己簡(jiǎn)單的封裝,大家還可以繼續(xù)完善.如有問題請(qǐng)指出.感謝您的閱讀!