Swift 4 引入了一个新的 Codable
协议,它允许你序列化和反序列化自定义数据类型,而无需编写任何特殊代码,也无需担心丢失值类型。🎉
太棒了,不是吗?这个库可以帮助你编写更少的代码!它是 Alamofire
的一个扩展,可以将 JSON
数据转换为 Decodable
对象。
WWDC2017
有一个专门的会议讨论了这项新特性 - Foundation 中的新内容让我们解码一个简单的 json 文件
{
"result": {
"libraries": [
{
"name": "Alamofire",
"stars": 23857,
"url": "https://github.com/Alamofire/Alamofire",
"random_date_commit": 1489276800
},
{
"name": "RxSwift",
"stars": 9600,
"url": "https://github.com/ReactiveX/RxSwift",
"random_date_commit": 1494547200
}
]
}
}
使用以下 Swift 模型
private struct Repo: Decodable {
let name: String
let stars: Int
let url: URL
let randomDateCommit: Date
private enum CodingKeys: String, CodingKey {
case name
case stars
case url
case randomDateCommit = "random_date_commit"
}
}
有一个与 responseData
, responseJSON
类似的方法 - responseDecodableObject
func responseDecodableObject<T: Decodable>(queue: DispatchQueue? = nil, keyPath: String? = nil, decoder: JSONDecoder = JSONDecoder(), completionHandler: @escaping (AFDataResponse<T>) -> Void)
queue
- 完成处理程序被调度的队列。keyPath
- 应该执行对象解码的 keyPath。decoder
- 执行 JSON 解码为语义 Decodable
类型的解码器。let url = URL(string: "https://raw.githubusercontent.com/otbivnoe/CodableAlamofire/master/keypathArray.json")!
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .secondsSince1970 // It is necessary for correct decoding. Timestamp -> Date.
AF.request(url).responseDecodableObject(keyPath: "result.libraries", decoder: decoder) { (response: AFDataResponse<[Repo]>) in
let repo = response.value
print(repo)
}
DataResponse<[Repo]>
DataResponse<Repo>
CocoaPods 是 Swift 和 Objective-C Cocoa 项目的依赖管理工具。 它拥有超过一万八千个库,可以帮助你优雅地扩展项目。 你可以使用以下命令安装它
$ sudo gem install cocoapods
要集成 CodableAlamofire,只需将以下行添加到你的 Podfile
中
target 'Test' do
use_frameworks!
pod 'CodableAlamofire'
end
Carthage 是一个去中心化的依赖管理器,它可以构建你的依赖项并为你提供二进制框架。
你可以使用 Homebrew 使用以下命令安装 Carthage
$ brew update
$ brew install carthage
要使用 Carthage 将 CodableAlamofire 集成到你的 Xcode 项目中,请在你的 Cartfile
中指定它
github "Otbivnoe/CodableAlamofire"
运行 carthage update
来构建框架,并将构建的 CodableAlamofire.framework
拖到你的 Xcode 项目中。