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

Detailed explanation of AFN encapsulated network requests

php中世界最好的语言
php中世界最好的语言Original
2018-04-16 15:43:261767browse

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!

Statement:
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