自定义 Alamofire 的 response serializer
Alamofire 的 DataRequest 类针对二进制数据、字符串、json、属性列表提供了一系列方便解析的方法(内部实际上使用的是 Response Serializer),现在我们要针对服务端返回的数据格式定义我们自己的 Response Serializer。
假设服务器返回的数据格式是这样的:
{
"code": 0,
"datas": {
"name": "Jack",
"age": 13
},
"message": ""
}
其中 datas、message 对应的数据可能为空,我们来针对这个格式定义 Response Serializer。
从二进制数据到数据模型,直接使用 Swift 4 内置的 JSONDecoder 进行解析,所以,定义的模型需要遵从 Decodable 协议(下面的代码,我为了偷懒直接写了 Codable)。
struct Response<T: Codable>: Codable {
let code: Int
let datas: T?
let message: String?
}
struct Person: Codable {
let name: String
let age: Int
}
extension DataRequest {
static func customResponseSerializer<T: Codable>(type: T.Type) -> DataResponseSerializer<T> {
return DataResponseSerializer(serializeResponse: { (request, response, data, error) -> Result<T> in
guard error == nil else {
return .failure(error!)
}
let result = Request.serializeResponseData(response: response, data: data, error: nil)
switch result {
case .success(let validData):
do {
let entity = try JSONDecoder().decode(T.self, from: validData)
return .success(entity)
} catch {
return .failure(error)
}
case .failure(let error):
return .failure(error)
}
})
}
@discardableResult
func responseCustomObject<T: Codable>(queue: DispatchQueue? = nil,
type: T.Type,
completion: @escaping (DataResponse<T>) -> Void) -> Self {
return response(queue: queue, responseSerializer: Alamofire.DataRequest.customResponseSerializer(type: type), completionHandler: completion)
}
}
使用的时候,这样就好了:
Alamofire.request("http://mall.cnrmall.com/api/app/version_check").responseCustomObject(type: Response<VersionInfo>.self) { (response) in
switch response.result {
case .success(let value):
print(value)
case .failure(let error):
print("error: \(error.localizedDescription)")
}
}
自定义 Alamofire 的 response serializer的更多相关文章
- .net中自定义过滤器对Response内容进行处理
原文:http://www.cnblogs.com/zgqys1980/archive/2008/09/02/1281895.html 代码DEMO:http://files.cnblogs.com/ ...
- django (装饰器,母版继承,自定义,request对象,response对象)
1. 装饰器 1. def wrapper(fn): def inner(*args,**kwargs): 执行被装饰函数之前的操作 ret = fn(*args,** ...
- ios 设置head请求头,自定义head, read response header
AFHTTPSessionManager *manger = [AFHTTPSessionManager manager]; manger.securityPolicy = [AFSecurityPo ...
- Alamofire源码解读系列(九)之响应封装(Response)
本篇主要带来Alamofire中Response的解读 前言 在每篇文章的前言部分,我都会把我认为的本篇最重要的内容提前讲一下.我更想同大家分享这些顶级框架在设计和编码层次究竟有哪些过人的地方?当然, ...
- drf序列化高级、自定义只读只写、序列化覆盖字段、二次封装Response、数据库查询优化(断关联)、十大接口、视图家族
目录 自定义只读 自定义只写 序列化覆盖字段 二次封装Response 数据库关系分析 断外键关联关系 ORM操作外键关系 ORM四种关联关系 基表 系列化类其他配置(了解) 十大接口 BaseSer ...
- Domain=com.alamofire.error.serialization.response Code=-1016 "Request failed: unacceptable content-type: text/html"
2015-11-16 10:39:17.235 PullDemo[338:60b] Application windows are expected to have a root view contr ...
- Alamofire 的使用
最近,AFNetworking 的作者Mattt Thompson提交了一个新的类似于 AFNetworking 的网络 基础库,并且是专门使用最新的 Swift 语言来编写的,名为:Alamofir ...
- Alamofire网络库基础教程
原文 Beginning Alamofire Tutorial 原文作者 Essan Parto译者 星夜暮晨(QQ:412027805) http://www.jianshu.com/p/f1208 ...
- Alamofire网络库进阶教程
本章节由CocoaChina翻译组成员星夜暮晨(博客)翻译自raywenderlich:Intermediate Alamofire Tutorial,敬请勘误. 欢迎回到我们的 Alamofire ...
随机推荐
- Top11 构建和测试API的工具
立刻像专业人士一样构建API 组织正在改变他们已经在软件应用项目中成功的微服务架构模型,这就是大多数微服务项目使用API(应用程序接口)的原因. 我们要为微服务喝彩,因为它相对于其他的模型有各种先进的 ...
- python学习——文件操作
打开文件 f = open(文件名, 文件打开模式,文件编码) ‘w’:只写模式,它是只能写,而不能读的.如果用’w’模式打开一个不存在的文件,则会创建新的文件开始写入:如果用’w’模式打开一个已存在 ...
- Javaweb之国际化
Javaweb之国际化 一.前言 软件的本地化:一个软件在某个国家或地区使用时,采用该国家或地区的语言,数字,货币,日期等习惯. 软件的国际化:软件开发时,让它能支持多个国家和地区的本地化应用.使得应 ...
- springboot-vue前后端分离session过期重新登录
springboot-vue前后端分离session过期重新登录 简单回顾cookie和session cookie和session都是回话管理的方式 Cookie cookie是浏览器端存储信息的一 ...
- pickle 序列化对象
# 序列化对象 import pickle mylist=[[1,2,3,4,5,6,7],["abc","xyz","hello"],[1 ...
- ABC133F - Colorful Tree
ABC133FColorful Tree 题意 给定一颗边有颜色和权值的树,多次询问,每次询问,首先更改颜色为x的边的权值为y,然后输出u到v的距离. 数据都是1e5量级的. 思路 我自己一开始用树链 ...
- Codeforces 935 C Fifa and Fafa
935 C 题意:Fifa想用wifi下载足球游戏, 但是Fafa是个流浪狂魔, 所以Fifa想让他的wifi在公寓里尽量覆盖最大的面积,并且不覆盖到Fafa和公寓外的人,fafa的坐标可以在公寓外. ...
- codeforces 816 C. Karen and Game(模拟+思维)
题目链接:http://codeforces.com/contest/816/problem/C 题意:给出一个矩阵,问能否从都是0的情况下只将一整行+1或者一整列+1变形过来,如果可以输出需要步数最 ...
- codeforces 509 D. Restoring Numbers(数学+构造)
题目链接:http://codeforces.com/problemset/problem/509/D 题意:题目给出公式w[i][j]= (a[i] + b[j])% k; 给出w,要求是否存在这样 ...
- Symmetric Matrix 牛客网暑期ACM多校训练营(第一场) B dp 组合数学
Count the number of n x n matrices A satisfying the following condition modulo m. * Ai, j ∈ {0, 1, 2 ...