SoFunction
Updated on 2025-04-13

IOS Network Requests for AFNetWorking Usage Details

Preface:

I plan to decouple the company's network requests from the business, so I want to learn about network requests. I recently learned about NSURLSession. Today I will learn about AFNetWorking, an excellent open source framework based on NSURLSession encapsulation. The ASIHttpRequest open source framework used when developing iOS for 13 years.

AFNetWorking

AFNetWorking is a lightweight open source framework for network requests, a high-performance framework that is extended based on iOS and mac os networks, which greatly reduces the difficulty of iOS development engineers to handle network requests and makes iOS development a pleasant thing.

Download address:AFNetworking_jb51.rar

1.) AFHTTPSessionManager requests administrator

-(AFHTTPSessionManager *)sharedManager
{
  AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
  //Maximum number of concurrent tasks requested   = 5;

  // Request format  // AFHTTPRequestSerializer binary format  // AFJSONRequestSerializer      JSON
  // AFPropertyListRequestSerializer PList (is a special XML, which is relatively easy to parse)  
   = [AFHTTPRequestSerializer serializer]; // Upload normal format  
  // Timeout time   = 30.0f;
  // Set request header  [ setValue:@"gzip" forHTTPHeaderField:@"Content-Encoding"];
  // Set the received Content-Type   = [[NSSet alloc] initWithObjects:@"application/xml", @"text/xml",@"text/html", @"application/json",@"text/plain",nil];
  
  // Return to format  // AFHTTPResponseSerializer binary format  // AFJSONResponseSerializer      JSON
  // AFXMLParserResponseSerializer XML, can only return XMLParser, and you also need to parse it by proxy method yourself  // AFXMLDocumentResponseSerializer (Mac OS X)
  // AFPropertyListResponseSerializer  PList
  // AFImageResponseSerializer     Image
  // AFCompoundResponseSerializer combination  
   = [AFJSONResponseSerializer serializer];//Return to format JSON  //Set the content-type that returns C  =[[NSSet alloc] initWithObjects:@"application/xml", @"text/xml",@"text/html", @"application/json",@"text/plain",nil];

  return manager;
}

2.) Process get request

-(void)doGetRequest
{
  //Create a request address  NSString *url=@"/method";
  //Construction parameters  NSDictionary *parameters=@{@"name":@"yanzhenjie",@"pwd":@"123"};
  //AFN administrator calls the get request method  [[self shareAFNManager] GET:url parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
    //Return request and return progress    NSLog(@"downloadProgress-->%@",downloadProgress);
  } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
    //Request successfully returns data. Returns different data formats according to responseSerializer.    NSLog(@"responseObject-->%@",responseObject);
  } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    //Request failed    NSLog(@"error-->%@",error);
  }];
}

3.) Process post request

-(void)doPostRequestOfAFN
{
  //Create a request address  NSString *url=@"/postBody";
  //Construction parameters  NSDictionary *parameters=@{@"name":@"yanzhenjie",@"pwd":@"123"};
  //AFN administrator calls the get request method  [[self shareAFNManager] POST:url parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
    //Return request and return progress    NSLog(@"downloadProgress-->%@",uploadProgress);
  } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
    //Request successfully returns data. Returns different data formats according to responseSerializer.    NSLog(@"responseObject-->%@",responseObject);
  } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    //Request failed    NSLog(@"error-->%@",error);
  }];
}

4.) Process file upload

-(void)doUploadRequest
{
  // Create URL resource address  NSString *url = @"/upload";
  // Parameters  NSDictionary *parameters=@{@"name":@"yanzhenjie",@"pwd":@"123"};
  [[self shareAFNManager] POST:url parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[dat timeIntervalSince1970];
    NSString* fileName = [NSString stringWithFormat:@"file_%", a];
    
    [FileUtils writeDataToFile:fileName data:[@"upload_file_to_server" dataUsingEncoding:NSUTF8StringEncoding]];
    // Get data to convert it into data    NSString *filePath =[FileUtils getFilePath:fileName];
    // Splice the data into the request question    [formData appendPartWithFileURL:[NSURL fileURLWithPath:filePath] name:@"headUrl" fileName:fileName mimeType:@"application/octet-stream" error:nil];
    
  } progress:^(NSProgress * _Nonnull uploadProgress) {
    // Upload progress    NSLog(@"%lf",1.0 * / );
  } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
    //Request succeeds    NSLog(@"Request successful: %@",responseObject);
    
  } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    //Request failed    NSLog(@"Request failed: %@",error);
  }];
}

5.) Process file download

-(void)doDownLoadRequest
{
  NSString *urlStr =@"/blog/950883/201701/";
  // Set the requested URL address  NSURL *url = [NSURL URLWithString:urlStr];
  // Create a request object  NSURLRequest *request = [NSURLRequest requestWithURL:url];
  // Download task  NSURLSessionDownloadTask *task = [[self shareAFNManager] downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
    // Download progress    NSLog(@"The current download progress is:%lf", 1.0 *  / );
  } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
    // Download address    NSLog(@"Default download address %@",targetPath);
    //Simulate a path here. The real scene can calculate an md5 value based on the url as fileKey    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[dat timeIntervalSince1970];
    NSString* fileKey = [NSString stringWithFormat:@"/file_%", a];
    // Set the download path, get the cache address through the sandbox, and finally return the NSURL object    NSString *filePath = [FileUtils getFilePath:fileKey];
    return [NSURL fileURLWithPath:filePath]; // The returned address where the file is stored in the local sandbox  } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
    // Download the method to complete the call    NSLog(@"filePath---%@", filePath);
    NSData *data=[NSData dataWithContentsOfURL:filePath];
    UIImage *image=[UIImage imageWithData:data];
    // Refresh the interface...    UIImageView *imageView =[[UIImageView alloc]init];
    =image;
    [ addSubview:imageView];
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
      ();
      .mas_equalTo(CGSizeMake(300, 300));
    }];
  }];
  //Start the download task  [task resume];
}

6.) Network status monitoring

- (void)aFNetworkStatus{
  
  //Create a network monitor  AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
  
  /*The enumeration of the four states correspond to unknown network without data WiFi
    typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) {
    AFNetworkReachabilityStatusUnknown = -1, unknown
    AFNetworkReachabilityStatusNotReachable = 0, no network
    AFNetworkReachabilityStatusReachableViaWWAN = 1, Cellular Data Network
    AFNetworkReachabilityStatusReachableViaWiFi = 2, WiFi
    };
    */
  
  [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
    //Here is a block that monitors network changes. It can be written as switch for convenient    //You can write events at will in it    switch (status) {
      case AFNetworkReachabilityStatusUnknown:
        NSLog(@"Unknown network status");
        break;
      case AFNetworkReachabilityStatusNotReachable:
        NSLog(@"No network");
        break;
        
      case AFNetworkReachabilityStatusReachableViaWWAN:
        NSLog(@"Cellular Data Network");
        break;
        
      case AFNetworkReachabilityStatusReachableViaWiFi:
        NSLog(@"WiFi Network");
        break;
        
      default:
        break;
    }
    
  }] ;
  
  [manager startMonitoring];
}

AFNetWorking memory leak

Usually, we generally think that the manager ends with a singleton pattern, so we usually use AFNetWorking like this, as follows

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

In fact, we clicked in to check the source code and found that it was not a singleton, but an AFHTTPSessionManager object is instantiated every time. The source code is as follows

+ (instancetype)manager {
  return [[[self class] alloc] initWithBaseURL:nil];
}

So when we use AFNetWorking, we need to singleton encapsulate the AFHTTPSessionManager

+ (AFHTTPSessionManager *)sharedManager
{
  static AFHTTPSessionManager *manager = nil;
  static dispatch_once_t predicate;
  dispatch_once(&predicate, ^{
    manager = [AFHTTPSessionManager manager];
     = 5;
    =;
     = [[NSSet alloc] initWithObjects:@"application/xml", @"text/xml",@"text/html", @"application/json",@"text/plain",nil];
    [ setValue:@"gzip" forHTTPHeaderField:@"Content-Encoding"];
    
  });
  return manager;
}

AFNetWorking About HTTPS

Starting from January 1, 2017, Apple requires developers to enable HTTPS for applications submitted to the App Store by the end of the year to support the ATS (App Transport Security) technology introduced by iOS 9. But later, Apple issued a statement announcing the extension of this time limit, providing developers with more time to prepare. Apple has not announced a new deadline yet. So there are currently two solutions to deal with https.

The first method:

Block iOS ATS (App Transport Security), add the following code to the file

<key>NSAppTransportSecurity</key> 
  <dict> 
    <key>NSAllowsArbitraryLoads</key> 
    <true/> 
 </dict> 

The second method:

Configure https CA certificate, which uses the NSBundle to obtain the CA certificate. AFNetWorking provides the configuration of AFSecurityPolicy module.

+ (AFSecurityPolicy *)customSecurityPolicy{
  //Https CA certificate address  NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"XueLeTSHTTPS" ofType:@"cer"];
  //Get CA certificate data  NSData *cerData = [NSData dataWithContentsOfFile:cerPath];
  //Create AFSecurityPolicy object  AFSecurityPolicy *security = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
  //Set whether to allow untrusted certificates (certificate invalid, certificate time expires) to pass verification, default is NO.   = YES;
  //Whether to verify the CN (common name) field of the domain name certificate.  The default value is YES.   = NO;
  //Return the certificate used to verify the server according to the verification mode   = [NSSet setWithObject:cerData];
  return security;
}

Then set the securityPolicy property of the AFHTTPSessionManager to equal the custom AFSecurityPolicy.

Summarize:

A brief record of the basic use of AFNetWorking, which is convenient for future searches.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.