PromiseKit+OMGHTTPURLRQ+Codable+泛型 - 讓請(qǐng)求更加清爽清晰
可以通過cocoapods進(jìn)行安裝痹届,或者去GitHub上下載
pod 'PromiseKit'
pod 'PromiseKit/OMGHTTPURLRQ'
然后對(duì)Promise進(jìn)行下常用的擴(kuò)展
extension Promise where T == (data: Data, response: URLResponse) {
func asObject<T: Codable>() -> Promise<T> {
return map {
try JSONDecoder().decode(T.self, from: $0.data)
// ... 可針對(duì)返回的結(jié)果提前進(jìn)行處理 - 比如網(wǎng)絡(luò)錯(cuò)誤之類、登錄失效跳轉(zhuǎn)之類等
// $0.data 薇组、 $0.response
// let res = try? JSONDecoder().decode(Result<T>.self, from: $0.data)
// let code = res?.code
// let data = res?.data
// ....
}
}
}
使用例子:
一般后臺(tái)的返回結(jié)果
{
"code": 0,
"message": "登錄成功",
"data": {
"object":$object
}
}
data 可能有三種情況 ①對(duì)象{} ②數(shù)組[] ③空nil
所以可以聲明個(gè)最基本的模型,再用泛型處理data那個(gè)未知類型
struct Result<T: Codable>:Codable {
var code: Int
var message: String
var data: T?
}
struct EmprtyData:Codable { }
struct ObjectData:Codable {
var useranme: String
var userId: Int
//...
}
struct ArrayData:Codable {
var id: Int
var avatar: String
//...
}
Promise<Result<EmprtyData>> // data 為空時(shí)候
Promise<Result<ObjectData>> // data 為對(duì)象時(shí)候
Promise<Result<[ArrayData]>> // data 為數(shù)組時(shí)候
實(shí)際操作事例
struct UserModuleAPI {
static func register(obj: RegisterObj) -> Promise<Result<EmprtyData>> {
let json = obj.toDictionary()
return URLSession.shared.POST(NetWorks.api + "/v3/user/register", json: json).asObject()
}
static func getUserInfo(userid: Int) -> Promise<Result<ObjectData>> {
return URLSession.shared.GET(NetWorks.api + "/v3/user/\(userid)").asObject()
}
static func getFriendsList(userid: Int) -> Promise<Result<[ArrayData]>> {
return URLSession.shared.GET(NetWorks.api + "/v3/user/friends/\(userid)").asObject()
}
// ...
}
使用例子
override func viewDidLoad() {
super.viewDidLoad()
UserModuleAPI.getFriendsList(userid: 123456).done { res in
print(res.code)
print(res.message)
guard let data = res.data else { return }
print(data)
}.ensure {
print("always")
}.catch { print($0) }
}
如果后臺(tái)數(shù)據(jù)比較規(guī)范的話杈帐,可以移步到這里來
http://www.reibang.com/p/1d13d4b38a17