Swift USES AFN to encapsulate network request details

  • 2020-05-30 21:10:37
  • OfStack

preface

As you all know, we usually package network requests into a singleton in a project to ensure that the network requests Session of the whole project are the same.

Singleton pattern definition: a class has one and only one instance, and it is provided to the whole system by self-instantiation.

Import the 3rd party framework through cocoaPods

01- switch to project directory


cd  The project name 

02- initializes Pods


pod init

03- open Pods file


open Podfile

04 - edit Podfile


#  Set support for the lowest platform 
platform :ios, '8.0'

target 'TestSwiftMixAFN' do
 #  If it is Swift project , Need to add "use_frameworks!"
 use_frameworks!
pod "AFNetworking"

end

05 - Pods installation


pod install

Encapsulate the AFN network request tool

Create a utility class that inherits from AFHTTPSessionManager


import AFNetworking

class XMSessionManager: AFHTTPSessionManager {
 // ...
}

Create an instance of AFHTTPSessionManager with a singleton


///  Create a network request singleton 
static let shared: XMSessionManager = XMSessionManager()

----------------------------------------------------------------
///  If you need to set the properties of the request , Can be added in a closure 
///  In the first 1 On the next access, the closure is executed and the results are saved in  shared  In the constant 
 static let shared1: XMSessionManager = {

  //  Instantiate object 
  let manager = XMSessionManager()

  //  Sets the data type that the response deserializes 
  manager.responseSerializer.acceptableContentTypes?.insert("text/plain")

  //  Returns the object 
  return manager
 }()

3. Add the HTTP request method (GET/POST) by enumeration


///  The enumeration - Request method 
///
/// - GET: GET
/// - POST: POST
enum XMHTTPMethod {
 case GET
 case POST
}

4. Customize the network request method to call back the data after the request is completed through the closure


///  Encapsulates network request methods 
 ///
 /// - Parameters:
 /// - Method: GET/POST,  The default is GET request 
 /// - URLString:  Request the address 
 /// - parameters:  parameter 
 /// - completed:  End the callback 
 func request(Method:XMHTTPMethod = .GET, URLString: String,parameters: [String: AnyObject]?, completed:@escaping ((_ json: AnyObject?, _ isSuccess: Bool)->())) {

  ///  Define the successful callback closure 
  let success = { (task: URLSessionDataTask,json: Any?)->() in
   completed(json as AnyObject?,true)
  }

  ///  Define the failed callback closure 
  let failure = {(task: URLSessionDataTask?, error: Error)->() in
   completed(nil,false)
  }

  ///  By request method , Execute different requests 
  //  If it is  GET  request 
  if Method == .GET { // GET

   get(URLString, parameters: parameters, progress: nil, success: success, failure: failure)

  } else { // POST

   post(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
  }
 }

Use of network request tools


///GET  request 
  XMSessionManager.shared.request(URLString: "http:xxx", parameters: nil, completed:{(json: AnyObject?,isSuccess: Bool)-> () in

   //  The request is successful 
   if isSuccess {
    print(json ?? "")
   } else {
    print(" The request failed ")
   }
  })


///POST  request 
  XMSessionManager.shared.request(URLString: "www.xxx.xxx", parameters: ["key":"value" as AnyObject], completed:{(json: AnyObject?,isSuccess: Bool)-> () in
   //  The request is successful 
   if isSuccess {
    print(json ?? "")
   } else {
    print(" The request failed ")
   }
  })

conclusion


Related articles: