Swift MVP架構(gòu)實踐

前言

  • MVP 全稱:Model-View-Presenter
  • MVP架構(gòu)模式是從MVC演變過來的(很多架構(gòu)都是的)
  • MVP/MVC思想類似,由Presenter/Controller負(fù)責(zé)業(yè)務(wù)邏輯
    百度百科上已經(jīng)介紹的非常清楚和細(xì)致,關(guān)于MVP/MVC的介紹
    MVC架構(gòu)
MVP架構(gòu)

SwiftMVP Demo地址:
https://github.com/hellolad/Swift-MVP

當(dāng)你要用Swift開發(fā)項目的時候,總是想著找一些好用的東西,讓我們的的項目兼容性更好,效率更高,運行速度更快,當(dāng)然寫代碼也要更舒服。

抽了一點時間研究了一下MVP,并且用Swift方式實現(xiàn)了一遍,雖然只是一個例子,但是還是感覺到MVP的模型數(shù)據(jù)分離真的很好。

需要用到的Swift文件:
主要:

  • CacheModel.swift
  • CachePresenter.swift
  • CacheViewController.swift
  • CacheProtocol.swift
  • Presenter
    次要
  • HTTPClient.swift
  • HTTPResponseProtocol.swift
Presenter.swift
protocol Presenter {
  associatedtype T
  var view: T? { get set }
  mutating func initial(_ view: T)
}

extension CachePresenter: Presenter {}

Presenter協(xié)議,定義了一個屬性view, 和一個函數(shù)initial。
view的作用最后就是你傳進來的Controller。initial的作用是為了給view賦值,并且初始化一個httpClient,在后面可以看到。

HTTPClient.swift
struct HTTPClient {
//  typealias Paramters = Dictionary<String, Any>
  var reponseHandle: HTTPResponseProtocol?
  
  init(handle: HTTPResponseProtocol?) {
    self.reponseHandle = handle
  }
  
  func get(url: String) {
    let session = URLSession(configuration: URLSessionConfiguration.default)
    let request = URLRequest(url: URL(string: url)!)
    session.dataTask(with: request, completionHandler: {
      data, response, error in
      if error == nil {
        if let da = data,
          let any = try? JSONSerialization.jsonObject(with: da, options: .mutableContainers),
          let dict = any as? [String: Any] {
          self.reponseHandle?.onSuccess(object: dict)
        }
      } else {
        self.reponseHandle?.onFailure(error: error!)
      }
    }).resume()
  }
}

HTTPClient設(shè)置了一個代理屬性responseHandle,通過init函數(shù)給它賦值從而達(dá)到在CachePresenter里可以回調(diào)到它的兩個函數(shù)。get函數(shù)就是從服務(wù)器獲取數(shù)據(jù)。

HTTPResponseProtocol.swift
protocol HTTPResponseProtocol {
  
  func onSuccess(object: Dictionary<String, Any>)
  func onFailure(error: Error)
}

HTTPResponseProtocol定義了兩個函數(shù)需要你去實現(xiàn),一個是成功一個是失敗。

CacheModel.swift
struct CacheModel {
  var origin: String?
  var url: String?
  
  init() {
    // ?? This is CacheModel
  }
  
  static func fromJSON(_ dictionary: [String: Any]?) -> CacheModel? {
    if let json = dictionary {
      var cm = CacheModel()
      cm.origin = json["origin"] as? String
      cm.url = json["url"] as? String
      return cm
    }
    return nil
  }
}

網(wǎng)絡(luò)請求的數(shù)據(jù)用的是httpbin.org的一個測試請求返回的數(shù)據(jù)
http://httpbin.org/cache/2000
CacheModel定義了兩個屬性和一個靜態(tài)函數(shù)。

CacheProtocol.swift
protocol CacheProtocol {
  func onGetCacheSuccess(model: CacheModel?)
  func onGetCacheFailure(error: Error)
}

CacheProtocol是Controller遵從的協(xié)議,只有Controller遵從了這個協(xié)議,才能拿到從服務(wù)器拿到的CacheModel的值。

CachePresenter.swift (重點)
struct CachePresenter<U> where U: CacheProtocol {
  
  var view: U?
  mutating func initial(_ view: U) {
    self.view = view
    self.httpClient = HTTPClient(handle: self)
  }
  
  var httpClient: HTTPClient?
  init() {}
  
  typealias Value = Int
  func getCache(by integer: Value) {
    // 網(wǎng)絡(luò)請求 ...
    self.httpClient?.get(url: "http://httpbin.org/cache/\(integer)")
  }
}

extension CachePresenter: HTTPResponseProtocol {
  func onSuccess(object: Dictionary<String, Any>) {
    view?.onGetCacheSuccess(model: CacheModel.fromJSON(object))
  }
  
  func onFailure(error: Error) {
    print(error)
  }
}
  • CachePresenter類指定了一個泛型U, U指定了必須是實現(xiàn)了CacheProtocol協(xié)議的類,我們知道上面我們說到實現(xiàn)CacheProtocol的類是Controller。
  • 之后我們實現(xiàn)了Presenter協(xié)議的屬性和函數(shù)分別給它賦值,上面我們說了在inital函數(shù)里初始化了httpClient并且它的responseProtocol是CachePresenter。
  • 實現(xiàn)HTTPResponseProtocol協(xié)議 onSuccess, onFailure
    最后我們的get函數(shù)拿到的數(shù)據(jù)并把數(shù)據(jù)代理到當(dāng)前的onSuccess函數(shù),然后我們的Presenter的view是一個CacheProtocol,所以它可以調(diào)用onGetCacheSuccess,然后CacheProtocol又是Controller實現(xiàn)的,最后就完成了一個閉環(huán)。
CacheViewController.swift
class CacheViewController: UIViewController {
  private var cachePresenter = CachePresenter<CacheViewController>()
  
  override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
    super.init(nibName: nil, bundle: nil)
    
    self.cachePresenter.initial(self)
  }
  required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    reloadData()
  }
  
  func reloadData() {
    // 請求網(wǎng)絡(luò)
    self.cachePresenter.getCache(by: 2000)
  }
  
}

extension CacheViewController: CacheProtocol {
  
  // 獲取成功
  func onGetCacheSuccess(model: CacheModel?) {
    dump(model)
    
    DispatchQueue.main.async {
      self.view.backgroundColor = .white
      let lab = UILabel()
      lab.textColor = .black
      lab.textAlignment = .center
      lab.text = "\(model?.origin ?? "") \n \(model?.url ?? "")"
      lab.numberOfLines = 2
      lab.frame = CGRect(x: 0, y: 100, width: UIScreen.main.bounds.width, height: 200)
      self.view.addSubview(lab)
    }
  }
  
  // 獲取失敗
  func onGetCacheFailure(error: Error) {
    dump(error)
  }
}

CacheViewController 初始化cachePresenter,并把自己self交給cachepresenter的initial函數(shù)。在reloadData里調(diào)用get函數(shù)從服務(wù)器獲取數(shù)據(jù),最后經(jīng)過CachePresenter拿到代理函數(shù),最后將數(shù)據(jù)賦值給Label顯示。

最重要的類是CachePresenter它負(fù)責(zé)獲取數(shù)據(jù),并和model,view進行交互。

-- Finished --

參考:

其他:

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容