1. I believe that most companies can use AFNetworking because it is an open source framework, safe and efficient. To improve efficiency and code maintainability, we need to repackage AFN.

###2, there is a problem with an old project, which needs to carry out IPV6 migration (although the old version of AFN also supports IPV6), but the method has changed, before there is no encapsulation of AFN, the project uses a lot of places, thousands of interfaces, so AFN appears in thousands of places. After updating AFN, old methods are no longer supported. If new methods are needed, thousands of methods need to be replaced, which is a lot of work. This is where the benefits of encapsulation come in, just one change.

###3: Secondary encapsulation of AFNetworking

## Here’s the point


####AFNetworking package :OC version

First of all, don’t ask why……

cocoapods pod ‘AFNetworking’


# # # # pay attention to the point

  • SharedAFHTTPSessionManagerObject instead of creating it every timeSessionManagerWhy share? Let me tell you something:HTTPThe protocol is based onTCPAgreement, so every timeHTTPBoth the client side and the server side need to go through before the request can be madeTCPThe three-way handshake of the connection, that is, before each request, the network data has been back and forth between the client and the server three times as shown below:

So the whole point of doing this is to make requests more efficient, so here’s what I did. Look at the next step

  • Create a singleton request object create a class that inherits fromAFHTTPSessionManagerThat is as follows:

####2. Encapsulation method

  • It encapsulates several common methods :get,post, upload, and download.Why class methods? Because it is easy to use!!
@interface AFNHelper: AFHTTPSessionManager // Singleton + (AFNHelper *)sharedManager; /** * GET request ** @param URL Interface URL * @param parameters parameter * @param success Request successful block * @param failure request failed block */ + (void)get:(NSString *)url parameter:(id )parameters success:(void(^)(id responseObject))success faliure:(void(^)(id error))failure; /** * post request ** @param URL Interface URL * @param parameters parameter * @param success Request successful block * @param failure request failed block */ + (void)post:(NSString *)url parameters:(id)parameters success:(void(^)(id responseObject))success faliure:(void(^)(id error))failure; /** * @param URL Interface URL * @param parameters parameter * @param success Request successful block * @param failure request failed block */ + (void)postNoBaseUrl:(NSString *)url parameters:(id)parameters success:(void(^)(id responseObject))success faliure:(void(^)(id error))failure; /** * file upload ** @param URL Interface URL * @param parameters * @param block picture data * @param success Request successful block * @param Failure attempt failed block * / + (void) post: (nsstrings *) url parameters (id) the parameters constructingBodyWithBlock: (void (^) (id <AFMultipartFormData> formData))block success:(void (^)(id responseObject))success faliure:(void (^)(id error))failure; /** * file download ** @param request download request * @param ProgressBlock download ProgressBlock * @param savePath savePath * @param failure download 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;Copy the code
  • The implementation of.m is as followsBaseUrlIs the macro
#import "AFNHelper.h"

@implementation AFNHelper

//单例实现
+ (AFNHelper *)sharedManager {
   
   static AFNHelper *handle = nil;
   
   static dispatch_once_t onceToken;
   dispatch_once(&onceToken, ^{
       handle = [AFNHelper manager];
     // 设置可接受的类型
       handle.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain"The @"application/json"The @"text/json"The @"text/javascript"The @"text/html",nil];
    
      
   });
   
   returnhandle; //get request + (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 request + (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); }]; } / / file upload + (void) post: (nsstrings *) url parameters (id) the 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); }]; } // file download + (void)downloadTaskWithUrl:(NSString *)url progress:(void (^)(id downloadProgress))ProgressBlock savePath:(NSString *)savePath completionHandler:(void (^)(NSURLResponse *response ,NSURL *filePath))completion Error :(void (^)(id error))failure{// create request NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[BaseUrl stringByAppendingString:url]]]; / / create a task 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); }}]; // Start the task [download resume]; } @endCopy the code

####3. How to use it

In this case, the basic encapsulated implementation of OC is ok

####AFNetworking package: Swift edition

  • Swift basic grammar, I will not say more, can use this, must be able to understand the grammar…..

Iop Cocoapods Pod ‘AFNetworking’

####1. Create a singleton request object create a class derived from AFHTTPSessionManager as follows:

####2. Concrete implementation methods are also commonly used four methods

/** get request -parameter urlString: request urlString -parameter parameters parameters: request success -parameter failure: Request failed callback * / class func get (urlString: String, the parameters: AnyObject? ,success:((responseObject:AnyObject?) -> Void)? ,failure:((error:NSError) -> Void)?) -> Void { AFNHelper.shareManager.GET(urlString, parameters: parameters, progress: { (progress)in
            
            }, success: { (task, responseObject) in// If responseObject is not emptyifresponseObject ! = nil { success! (responseObject:responseObject) } }) { (task, error)infailure! (error:error)}} /** post request -parameter urlString: request urlString -parameter parameters: request urlString -parameter success: Request success callback - parameter failure: failed to request correction * / class func post (urlString: String, the parameters: AnyObject? ,success:((responseObject:AnyObject?) -> Void)? ,failure:((error:NSError) -> Void)?) -> Void { AFNHelper.shareManager.POST(urlString, parameters: parameters, progress: { (progress)in
            
            }, success: { (task, responseObject) in// If responseObject is not emptyifresponseObject ! = nil { success! (responseObject:responseObject) } }) { (task, error)infailure! (error:error)}} /** File upload -parameter urlString: request urL-parameter parameters: Request parameters - parameter constructingBodyWithBlock: file data - parameter uploadProgress: upload progress - parameter success: */ 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)inconstructingBodyWithBlock! (formData:formData) }, progress: { (progress)inuploadProgress! (progress:progress) }, success: { (task, objc)in
                
                ifobjc ! = nil { success! (responseObject:objc) } }) { (task, error)infailure! (error:error)}} /** Download file -parameter request: request - parameter downloadProgressBlock: -parameter savePath: storage path -parameter completionHandler: callback after completion */ class func downloadTaskWithRequest(request: NSURLRequest, downloadProgressBlock: ((downloadProgress :NSProgress) -> Void)? , savePath: String,completionHandler:((response:NSURLResponse, error:NSError?) -> Void)?) -> Void{// Create a download tasklet task  =  AFNHelper.shareManager.downloadTaskWithRequest(request, progress: { (progress) indownloadProgressBlock! (downloadProgress:progress) }, destination: { (url, response) -> NSURLin
                
                
                return NSURL(fileURLWithPath: savePath)
            }) { (response, url, error) in
                
                if(error == nil) { completionHandler! (Response :response,error:error)}} // Start downloading task.resume()}Copy the code

####3. How to use a screenshot as follows:

The above is the SWIFT version of THE AFN package, after reading it feels very simple


The above is just my own simple encapsulation, you can continue to improve. Please point out any questions. Thank you for reading!