Detailed explanation of AFN encapsulated network requests
This time I will bring you a detailed explanation of AFN encapsulated network requests. What are the precautions for AFN encapsulated network requests? The following is a practical case, let’s take a look.
I believe everyone knows that in a project, we usually encapsulate network requests into a singleton to ensure that the network requests Session of the entire project are the same.
Single case modeDefinition: A class has one and only one instance, and it is instantiated and provided to the entire system. I won’t say much below, let’s take a look at the detailed introduction.
Import third-party frameworks through cocoaPods
01-Switch to the project directory
cd 项目名称
02-Initialize Pods
pod init
03-Open Pods file
open Podfile
04-Edit Podfile
# 设置支持最低平台 platform :ios, '8.0' target 'TestSwiftMixAFN' do # 如果是Swift项目,需添加"use_frameworks!" use_frameworks! pod "AFNetworking" end
05-Install Pods
pod install
Encapsulation 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
/// 创建网络请求单例 static let shared: XMSessionManager = XMSessionManager() ---------------------------------------------------------------- /// 如果需要设置请求的属性,可在闭包中添加 /// 在第一次访问时,执行闭包,并且将结果保存在 shared 常量中 static let shared1: XMSessionManager = { // 实例化对象 let manager = XMSessionManager() // 设置响应反序列化支持的数据类型 manager.responseSerializer.acceptableContentTypes?.insert("text/plain") // 返回对象 return manager }()
3 Through enumeration, add HTTP request method(GET/POST)
/// 枚举-请求方法 /// /// - GET: GET /// - POST: POST enum XMHTTPMethod { case GET case POST }
4 Customize the network request method and request the completed data through the closure callback
/// 封装网络请求方法 /// /// - Parameters: /// - Method: GET/POST, 默认是GET请求 /// - URLString: 请求地址 /// - parameters: 参数 /// - completed: 结束回调 func request(Method:XMHTTPMethod = .GET, URLString: String,parameters: [String: AnyObject]?, completed:@escaping ((_ json: AnyObject?, _ isSuccess: Bool)->())) { /// 定义成功回调闭包 let success = { (task: URLSessionDataTask,json: Any?)->() in completed(json as AnyObject?,true) } /// 定义失败回调闭包 let failure = {(task: URLSessionDataTask?, error: Error)->() in completed(nil,false) } /// 通过请求方法,执行不同的请求 // 如果是 GET 请求 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 The use of network request tools
///GET 请求 XMSessionManager.shared.request(URLString: "http:xxx", parameters: nil, completed:{(json: AnyObject?,isSuccess: Bool)-> () in // 请求成功 if isSuccess { print(json ?? "") } else { print("请求失败") } }) ///POST 请求 XMSessionManager.shared.request(URLString: "www.xxx.xxx", parameters: ["key":"value" as AnyObject], completed:{(json: AnyObject?,isSuccess: Bool)-> () in // 请求成功 if isSuccess { print(json ?? "") } else { print("请求失败") } })
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!
Recommended reading:
The above is the detailed content of Detailed explanation of AFN encapsulated network requests. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics










![WLAN expansion module has stopped [fix]](https://img.php.cn/upload/article/000/465/014/170832352052603.gif?x-oss-process=image/resize,m_fill,h_207,w_330)
If there is a problem with the WLAN expansion module on your Windows computer, it may cause you to be disconnected from the Internet. This situation is often frustrating, but fortunately, this article provides some simple suggestions that can help you solve this problem and get your wireless connection working properly again. Fix WLAN Extensibility Module Has Stopped If the WLAN Extensibility Module has stopped working on your Windows computer, follow these suggestions to fix it: Run the Network and Internet Troubleshooter to disable and re-enable wireless network connections Restart the WLAN Autoconfiguration Service Modify Power Options Modify Advanced Power Settings Reinstall Network Adapter Driver Run Some Network Commands Now, let’s look at it in detail

This article will introduce the solution to the problem that the globe symbol is displayed on the Win10 system network but cannot access the Internet. The article will provide detailed steps to help readers solve the problem of Win10 network showing that the earth cannot access the Internet. Method 1: Restart directly. First check whether the network cable is not plugged in properly and whether the broadband is in arrears. The router or optical modem may be stuck. In this case, you need to restart the router or optical modem. If there are no important things being done on the computer, you can restart the computer directly. Most minor problems can be quickly solved by restarting the computer. If it is determined that the broadband is not in arrears and the network is normal, that is another matter. Method 2: 1. Press the [Win] key, or click [Start Menu] in the lower left corner. In the menu item that opens, click the gear icon above the power button. This is [Settings].

LOL cannot connect to the server, please check the network. In recent years, online games have become a daily entertainment activity for many people. Among them, League of Legends (LOL) is a very popular multiplayer online game, attracting the participation and interest of hundreds of millions of players. However, sometimes when we play LOL, we will encounter the error message "Unable to connect to the server, please check the network", which undoubtedly brings some trouble to players. Next, we will discuss the causes and solutions of this error. First of all, the problem that LOL cannot connect to the server may be

1. Check the wifi password: Make sure the wifi password you entered is correct and pay attention to case sensitivity. 2. Confirm whether the wifi is working properly: Check whether the wifi router is running normally. You can connect other devices to the same router to determine whether the problem lies with the device. 3. Restart the device and router: Sometimes, there is a malfunction or network problem with the device or router, and restarting the device and router may solve the problem. 4. Check the device settings: Make sure the wireless function of the device is turned on and the wifi function is not disabled.

Windows operating system is one of the most popular operating systems in the world, and its new version Win11 has attracted much attention. In the Win11 system, obtaining administrator rights is an important operation. Administrator rights allow users to perform more operations and settings on the system. This article will introduce in detail how to obtain administrator permissions in Win11 system and how to effectively manage permissions. In the Win11 system, administrator rights are divided into two types: local administrator and domain administrator. A local administrator has full administrative rights to the local computer

In daily life and work, we often need to share files and folders between different devices. Windows 11 system provides convenient built-in folder sharing functions, allowing us to easily and safely share the content we need with others within the same network while protecting the privacy of personal files. This feature makes file sharing simple and efficient without worrying about leaking private information. Through the folder sharing function of Windows 11 system, we can cooperate, communicate and collaborate more conveniently, improving work efficiency and life convenience. In order to successfully configure a shared folder, we first need to meet the following conditions: All devices (participating in sharing) are connected to the same network. Enable Network Discovery and configure sharing. Know the target device

In order to use our computer, in addition to some hardware, it also needs to be connected to a stable network. Many friends have discovered that the network in the computer is divided into public network and private network. Many people are curious about how to convert the public network into a private network. . Win10 Home Edition public network is changed to a private network 1. Advanced settings of the Advanced Sharing Center 1. First, we directly press the win+R shortcut key combination to summon the run pop-up window, then enter "control panel" here, and click OK to open the control panel . 2. Then we select Network and Internet--Network and Sharing Center--Change advanced sharing settings. 3. Then we click on the dedicated option in the more advanced sharing settings interface and check the "Enable

Detailed explanation of division operation in OracleSQL In OracleSQL, division operation is a common and important mathematical operation, used to calculate the result of dividing two numbers. Division is often used in database queries, so understanding the division operation and its usage in OracleSQL is one of the essential skills for database developers. This article will discuss the relevant knowledge of division operations in OracleSQL in detail and provide specific code examples for readers' reference. 1. Division operation in OracleSQL
