从nsurlsession、Alamofire到moya

更好的理解(抽象)、更少的构建(配置)、更方便的表达(语言)

一、iOS系统的网络编程(DSL概念)

ios缺省的网络编程只是给出了网络编程的基本概念:

urlsession、request、responde、缓存、会话、鉴权体系等;

给出了DSL的基本概念;

需要程序员自己根据需要对这些概念进行组装,生成自己的网络通信系统;

二、Alamofire(机制、构建)

可配置、易管理、层次清晰的网络通信模块。

Alamofire在iOS网络编程系统概念的基础上,进行了一系列的组装;

组装的结果是对七层网络通信模型的上三层:应用、表示、会话控制的缺省操作进行了一系列的完善。

1、应用层

  • Upload File / Data / Stream / MultipartFormData
  • Download File using Request or Resume Data
  • Network Reachability

2、表示层

URL / JSON / plist Parameter Encoding

3、会话层

Authentication with URLCredential

TLS Certificate and Public Key Pinning

Upload and Download Progress Closures with Progress

Dynamically Adapt and Retry Requests

给应用提供了一系列便捷的网络管理配置接口,和网络调用接口;

Alamofire.request("https://httpbin.org/get", method: .get, parameters: nil, encoding: URLEncoding.default, headers: nil).responseJSON { (response) in

 if(response.error == nil){

 LLog("请求成功")

 LLog(response.result.value)

 }else{

 LLog("请求失败(String(describing: response.error))")

 }

}

三、Moya(表达、构建)

1、swift的语言风格抽象:enum、protocol、扩展

网络请求的构建、表达:使用枚举关联值定义扩展具体的请求

2、通过引入closure和通用代理机制更好的抽象了通信生命和会话管理机制。

3、通过rxswift扩展获取了更好的函数式编程的pipeline处理流程构建能力。

https://github.com/Moya/Moya/blob/master/Readme_CN.md

https://github.com/LeoMobileDeveloper/Blogs/blob/master/Swift/AnaylizeMoya.md

原文地址:https://www.cnblogs.com/feng9exe/p/11655086.html