Preface
I believe everyone knows that in a project, network requests are generally encapsulated into a singleton to ensure that the entire project's network request Session is the same.
Singleton pattern definition: A class has and only one instance, and it is instantiated to the entire system by itself. I won’t say much about it below, let’s take a look at the detailed introduction together.
Import third-party frameworks through cocoaPods
01-Switch to project directory
cd Project name
02-Initialize Pods
pod init
03-Open Pods file
open Podfile
04-Edit Podfile
# Set the minimum platform to supportplatform :ios, '8.0' target 'TestSwiftMixAFN' do # If it is a Swift project, you need to add "use_frameworks!" use_frameworks! pod "AFNetworking" end
05-Installation Pods
pod install
Encapsulated AFN network request tool
1 Create a tool class, inherited from AFHTTPSessionManager
import AFNetworking class XMSessionManager: AFHTTPSessionManager { // ... }
2 Create an AFHTTPSessionManager instance through a singleton
/// Create a single instance of network requeststatic let shared: XMSessionManager = XMSessionManager() ---------------------------------------------------------------- /// If you need to set the requested attribute, you can add it in the closure/// On the first access, the closure is executed and the result is saved in a shared constant static let shared1: XMSessionManager = { // Instantiate the object let manager = XMSessionManager() // Set the data type supported by response deserialization ?.insert("text/plain") // Return object return manager }()
3 Add HTTP request method (GET/POST) through enumeration
/// Enumeration - Request method/// /// - GET: GET /// - POST: POST enum XMHTTPMethod { case GET case POST }
4 Customize the network request method, data after the closure callback request is completed
/// Encapsulate network request method /// /// - Parameters: /// - Method: GET/POST, default is GET request /// - URLString: Request address /// - parameters: parameters /// - completed: End callback func request(Method:XMHTTPMethod = .GET, URLString: String,parameters: [String: AnyObject]?, completed:@escaping ((_ json: AnyObject?, _ isSuccess: Bool)->())) { /// Define a successful callback closure let success = { (task: URLSessionDataTask,json: Any?)->() in completed(json as AnyObject?,true) } /// Define failed callback closure let failure = {(task: URLSessionDataTask?, error: Error)->() in completed(nil,false) } /// Execute different requests through the request method // If it is a 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) } }
5. Use of network request tools
///GET request (URLString: "http:xxx", parameters: nil, completed:{(json: AnyObject?,isSuccess: Bool)-> () in // Request succeeded if isSuccess { print(json ?? "") } else { print("Request failed") } }) ///POST request (URLString: "", parameters: ["key":"value" as AnyObject], completed:{(json: AnyObject?,isSuccess: Bool)-> () in // Request succeeded if isSuccess { print(json ?? "") } else { print("Request failed") } })
Summarize
The above is the entire content of this article. I hope that the content of this article has a certain reference value for everyone's study or work. If you have any questions, you can leave a message to communicate. Thank you for your support.