快速解析模型工具,支持RxSwift。同时支持缓存功能 【相关手册 https://MoyaMapper.github.io 】
Moya
版本 >=14.0.0
iOS
版本 >=10.0
语法更新至 Swift 5.0
使用Carthage需要特别注意
Cache
的指定,需指定为github "Igor-Palaguta/Cache" "560f00a9a9549db161ca70d96eed74fc580b03e3"
Moya 13.0
版本还未支持RxSwift 5.0.1
,所以 RxSwift
的版本不能指定 5.0
及以上现在Data、字典、json字符串 等都可以转为 Modelable
/// Modelable -> mapping -> Model
static func mapModel(from object: Any) -> Self
/// Modelable -> mapping -> Models
static func mapModels(from object: Any) -> [Self]
/// Codeable -> Model
static func codeModel(from object: Any) -> Self
/// Codeable -> Models
static func codeModels(from object: Any) -> [Self]
Example
let model = models[0]
let jsonData = model.toData()
let jsonDict = model.toDictionary()
let jsonString = model.toJSONString()
let model1 = MyModel.mapModel(from: jsonData!)
let model2 = MyModel.mapModel(from: jsonDict)
let model3 = MyModel.mapModel(from: jsonString)
struct AAA: Modelable {
var c1: String = ""
mutating func mapping(_ json: JSON) {
c1 = json["cc"].stringValue
}
}
struct BBB: Modelable {
var d1: [AAA] = []
var goodJob: String = ""
var d3: Int = 0
mutating func mapping(_ json: JSON) {
d1 = AAA.mapModels(from: json["d2"].rawString() ?? "")
}
// 定义解析策略
func keyDecodingStrategy() -> MMJSONDecoder.KeyDecodingStrategy {
return .convertFromSnakeCase
}
// 定义默认值策略
func customDefaultValueStrategy() -> MMJSONDecoder.NotFoundKeyOrValueDecodingStrategy {
return .customDefaultValue(MyCustomDefaultValue())
}
}
// 定义自己的默认值
struct MyCustomDefaultValue: MMJSONDefault {
var boolValue: Bool { return true }
var intValue: Int { return 1 }
var int8Value: Int8 { return 1 }
var int16Value: Int16 { return 1 }
var int32Value: Int32 { return 1 }
var int64Value: Int64 { return 1 }
var uIntValue: UInt { return 1 }
var uInt8Value: UInt8 { return 1 }
var uInt16Value: UInt16 { return 1 }
var uInt32Value: UInt32 { return 1 }
var uInt64Value: UInt64 { return 1 }
var floatValue: Float { return 1 }
var doubleValue: Double { return 1 }
var stringValue: String { return "1" }
}
Carthage 拉取指定版本代码并编译为 .Framework 文件
carthage update --no-use-binaries --platform ios
Carthage 测试 Framework
carthage build --no-skip-current --platform ios
MMCache+Response.swift :86
TemplateParameter
必须包含init方法,否则使用时会遇到 initializer is inaccessible due to 'internal' protection level
子Framework使用时要注意在恰当的位置进行导入父Framework
#if !COCOAPODS
import MoyaMapper
#endif
fetchStatusCode
方法,方便获取接口返回的状态码/// 获取接口返回的状态码
///
/// - Parameters:
/// - path: JSON数据路径 (默认为模型数据路径)
/// - keys: 目标数据子路径 (例: [0, "_id"])
/// - Returns: 接口返回的状态码
func fetchStatusCode(
path: String? = nil,
keys: [JSONSubscriptType] = []
) -> String
// 配合 MoyaMapperPlugin 使用
let code = response.fetchStatusCode()
MoyaMapperPlugin
: 修复 ModelableParameter
失效问题MoyaMapperPlugin
: 完善对请求失败的捕捉alwaysFetchCache