Home > Web Front-end > JS Tutorial > Detailed explanation of AFN encapsulated network requests

Detailed explanation of AFN encapsulated network requests

php中世界最好的语言
Release: 2018-04-16 15:43:26
Original
1740 people have browsed it

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 项目名称
Copy after login

02-Initialize Pods

pod init
Copy after login

03-Open Pods file

open Podfile
Copy after login

04-Edit Podfile

# 设置支持最低平台
platform :ios, '8.0'
target 'TestSwiftMixAFN' do
 # 如果是Swift项目,需添加"use_frameworks!"
 use_frameworks!
pod "AFNetworking"
end
Copy after login

05-Install Pods

pod install
Copy after login

Encapsulation AFN network request tool

1 Create a tool class, inherited from AFHTTPSessionManager

import AFNetworking
class XMSessionManager: AFHTTPSessionManager {
 // ...
}
Copy after login

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
 }()
Copy after login

3 Through enumeration, add HTTP request method(GET/POST)

/// 枚举-请求方法
///
/// - GET: GET
/// - POST: POST
enum XMHTTPMethod {
 case GET
 case POST
}
Copy after login

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)
  }
 }
Copy after login

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("请求失败")
   }
  })
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template