RxSwift+Moya+ObjectMapper優雅的網絡請求本人已寫了一個開源的拿來即用的Swift項目架構 可以參考此架構來通篇閱讀此文章更有幫助 有喜歡的還望送人玫瑰手留餘香哦 當然這個拿來即用的Swift項目架構有不合理的地方 還望大神指點一二
末尾有彩蛋
文章目錄 一 Rxswift 簡單介紹 二 Moya 簡單介紹以及使用 三 ObjectMapper 簡單介紹以及使用 四 RxSwift+Moya+ObjectMapper優雅的網絡請求及模型轉換
一 RxSwift 簡單介紹
- RxSwift是Swift函數響應式程式設計的一個開源庫,由GitHub的ReactiveX組織開發和維護
- 其他語言像C#,Java 和JS也有: Rx.Net、RxJava、RxJS
- RxSwift的目的是讓資料/事件流和異步任務能夠更友善的序 列化處理 能夠使用Swift進行響應式程式設計 本文就不詳細介紹Rxswift 樓主之前寫過RxSwift 的介紹以及使用 可以參看一下 RxSwift 個人學習筆記記錄
二 Moya 簡單介紹以及使用
1 Moya 簡單介紹
Moya是一個基于Alamofire的Networking library,并且添加了對于ReactiveCocoa和RxSwift的接口支援,大大簡化了開發過程,是Reactive Functional Programming的網絡層首選。
Github上的官方介紹羅列了Moya的一些特點:
- 編譯的時候會檢查API endpoint
- 可以用枚舉值清楚地定義很多endpoint
- 增加了stubResponse類型,大大友善了unit testing
2 Moya 的 使用
首先我們需要聲明一個enum來對請求進行明确分類。
enum APIManager{
case GetHomeList // 擷取首頁清單
case GetHomeDetail(Int) // 擷取詳情頁
}
複制代碼
然後我們需要讓這個enum遵守TargetType協定,在這個協定中可以看到 TargetType定義了我們發送一個網絡請求所需要的東西,baseURL,parameter,method等一些計算性屬性,我們要做的就是去實作這些東西,當然有帶預設值的我們可以不去實作。
extension APIManager: TargetType {
/// The target's base `URL`.
var baseURL: URL {
return URL.init(string: "http://news-at.zhihu.com/api/")!
}
/// The path to be appended to `baseURL` to form the full `URL`.
var path: String {
switch self {
case .GetHomeList: // 不帶參數的請求
return "4/news/latest"
case .GetHomeDetail(let id): // 帶參數的請求
return "4/theme/\(id)"
}
}
// 區分get 和 post
var method: Moya.Method {
return .get
}
/// The parameters to be incoded in the request.
var parameters: [String: Any]? {
return nil
}
/// The method used for parameter encoding.
var parameterEncoding: ParameterEncoding {
return URLEncoding.default
}
/// Provides stub data for use in testing.
var sampleData: Data {
return "".data(using: String.Encoding.utf8)!
}
/// The type of HTTP task to be performed.
var task: Task {
return .request
}
/// Whether or not to perform Alamofire validation. Defaults to `false`.
var validate: Bool {
return false
}
}
複制代碼
寫好上邊的以後 我們就可以去發送一個請求了
private let provider = RxMoyaProvider<APIManager>()
// 請求資料
provider
.request(.GetHomeList)
.filterSuccessfulStatusCodes()
.mapJSON().subscribe(onNext: { (json) in
print(json)
}).addDisposableTo(bag)
複制代碼
上邊就是請求資料了 回調出來json資料
如果對RxSwift還不熟悉的話 建議去看一下之前寫的文章RxSwift 個人學習筆記記錄 Moya其實是提供了非常方面的RxSwift擴充 簡單介紹一下上邊方法和變量中的各個名詞:
- RxMoyaProvider是MoyaProvider的子類,是對RxSwift的擴充
- filterSuccessfulStatusCodes() 是Moya為RxSwift提供的擴充方法,顧名思義,可以得到成功成功地網絡請求,忽略其他的
- mapJSON() 也是Moya RxSwift的擴充方法,可以把傳回的資料解析成 JSON 格式 會傳回一個Observable 然後我們就可以對這個Observable進行訂閱了 然後我們就可以得到下邊的json資料 隻展示了部分資料 網絡請求就已經結束了 就這這麼簡單輕松and easy ?
{
date = 20170908;
stories = (
{
"ga_prefix" = 090817;
id = 9602715;
images = (
"https://pic2.zhimg.com/v2-3b39b83f560e089a7f6ddb00f6948b81.jpg"
);
title = "\U4e24\U5343\U591a\U5e74\U524d\Uff0c\U79e6\U56fd\U4e3a\U4ec0\U4e48\U8981\U7edf\U4e00\U4e2d\U56fd\Uff1f";
type = 0;
},
{
"ga_prefix" = 090816;
id = 9601590;
images = (
"https://pic4.zhimg.com/v2-700a8c29d04a885354d78d5a91a9fa5b.jpg"
);
title = "\U8fdc\U5904\U6765\U4e86\U8f66\Uff0c\U5148\U89c1\U5230\U8f66\U9876\U5c31\U8bf4\U660e\U5730\U7403\U662f\U5706\U7684\Uff1f\U4e0d\U53ef\U80fd\U7684";
type = 0;
},
);
"top_stories" = (
{
"ga_prefix" = 090815;
id = 9607829;
image = "https://pic3.zhimg.com/v2-14c13f9f87b1b3082929b444072eebb6.jpg";
title = "\U770b\U7167\U7247\Uff0c\U6211\U5c31\U77e5\U9053\U4f60\U662f\U540c\U6027\U604b\Uff0c\U65af\U5766\U798f\U5927\U5b66\U7684\U4eba\U5de5\U667a\U80fd\U8bf4";
type = 0;
},
{
"ga_prefix" = 090807;
id = 9606837;
image = "https://pic1.zhimg.com/v2-cceffc2e17185ae51b7b2d14b4414e84.jpg";
title = "\U6211\U8fd9\U4e48\U80d6\Uff0c\U5230\U5e95\U662f\U56e0\U4e3a\U5403\U5f97\U592a\U591a\U8fd8\U662f\U52a8\U5f97\U592a\U5c11\Uff1f";
type = 0;
},
);
}
複制代碼
三 ObjectMapper 簡單介紹以及使用
json得到了 接下來那就是json轉模型了
ObjectMapper 是一個在 Swift 下資料轉模型的非常好用,并且很 Swift 的一個架構。以前我們在寫 OC 代碼的時候用 MJExtension 轉模型,到了 Swift 的時代趕緊将 ObjectMapper 使用起來吧。
為了支援映射,類或者結構體隻需要實作Mappable協定。這個協定包含兩個方法 而且這兩個方法是必須實作的
class LLHomeModel: Mappable {
var date: String?
var stories: [StoryModel]?
var top_stories: [StoryModel]?
// 接下來的兩個方法是必須要實作的
required init?(map: Map) {
}
public func mapping(map: Map) {
date <- map["date"]
stories <- map["stories"]
top_stories <- map["top_stories"]
}
}
複制代碼
一旦你的對象實作了 Mappable, ObjectMapper就可以讓你輕松的實作和 JSON 之間的轉換。 把 JSON 字元串轉成 model 對象:
let homeModel = LLHomeModel(JSONString: JSONString)
複制代碼
把一個 model 轉成 JSON 字元串:
let JSONString = homeModel.toJSONString(prettyPrint: true)
複制代碼
還有一些具體的基礎使用可以參考ObjectMapper中文翻譯
四 RxSwift+Moya+ObjectMapper優雅的網絡請求及模型轉換
RxSwift結合MVVM 簡直的太合适不過了 我們将 網絡請求放在VM裡邊
private let provider = RxMoyaProvider<APIManager>()
// 請求資料
provider
.request(.GetHomeList)
.filterSuccessfulStatusCodes()
.mapJSON().mapObject(type: LLHomeModel.self).subscribe(onNext: { (model) in
self.modelObserable.value = model.stories!
}, onError: { (error) in
}).addDisposableTo(bag)
複制代碼
可以看到我們上邊代碼中
provider .request(.GetHomeList) .filterSuccessfulStatusCodes() .mapJSON().
這個方法本身應該得到 JSON的 但是我後邊跟了一個mapObject 的方法 這個方式可以直接根據json的格式轉換成模型 或者是模型數組 來看一下這個方法 我是單獨定義了一個json轉模型的類
LLToModelExtension.swift
extension Observable{
func mapObject<T:Mappable>(type: T.Type) -> Observable<T> {
return self.map { response in
guard let dict = response as? [String : Any] else{
throw RxSwiftMoyaError.ParseJSONError
}
return Mapper<T>().map(JSON: dict)!
}
}
func mapArray<T: Mappable>(type: T.Type) -> Observable<[T]> {
return self.map { response in
//if response is an array of dictionaries, then use ObjectMapper to map the dictionary
//if not, throw an error
guard let array = response as? [Any] else {
throw RxSwiftMoyaError.ParseJSONError
}
guard let dicts = array as? [[String: Any]] else {
throw RxSwiftMoyaError.ParseJSONError
}
return Mapper<T>().mapArray(JSONArray: dicts)
}
}
}
enum RxSwiftMoyaError: String {
case ParseJSONError
case OtherError
}
extension RxSwiftMoyaError: Swift.Error { }
複制代碼
介紹一下上邊代碼中各個方法以及名詞
- 1
方法是處理單個對象的mapObject
處理對象數組mapArray
- 2 如果傳進來的資料 是一個
的話 那麼就利用NSDictionary
的ObjectMapper
方法映射這些資料,這個方法會調用你之前在 mapping 方法裡面定義的邏輯。map
- 3 如果
不是一個response
, 那麼就抛出一個錯誤。dictionary
- 4 在底部自定義了簡單的 Error,繼承了 Swift 的 Error 類,在實際應用過程中可以根據需要提供自己想要的 Error。
彩蛋
可能會有人問 為什麼請求回來的資料 要指派給modelObserable.Value呢 而不是指派給一個模型數組 然後reloadData呢 這裡我用的RXSwift裡邊UItableView綁定資料的一個方法 再也不用寫一大串資料源方法了 這個也可以去這裡參考哦
var modelObserable = Variable<[StoryModel]> ([])
//MARK: Rx 綁定tableView資料
modelObserable.asObservable().bind(to: tableV.rx.items(cellIdentifier: cellID, cellType: LLHomeCell.self)){ row , model , cell in
cell.titleLbl.text = model.title
cell.imageV?.kf.setImage(with: URL.init(string: (model.images?.count)! > 0 ? (model.images?.first)! : ""))
}.addDisposableTo(bag)
複制代碼
Swift項目架構位址
參考文章 Moya入坑記 RxSwift+Moya