背景
由于后端采用 meteor.js 進(jìn)行開(kāi)發(fā),移動(dòng)端適配方案很容易讓人想到 web app 的開(kāi)發(fā)模式。但這種直接適配的方法有很強(qiáng)的局限性。雖然 hybrid 也已經(jīng)不是什么稀奇的方案,但 web 功能依舊和本地功能有一定的分離感。比如,meteor 監(jiān)聽(tīng)的某個(gè)資源想要和本地 API 獲取的其他資源在同一個(gè)列表中顯示。那單純的使用 web 是沒(méi)法解決的。唯一的辦法就是分別加載 meteor 和 API 資源,然后將他們整合在一起。那我們又該如何加載 meteor 的資源呢?
相關(guān)知識(shí)
通過(guò)調(diào)研發(fā)現(xiàn) meteor 的客戶(hù)端和服務(wù)端是通過(guò) DDP 進(jìn)行交互的。
DDP定義
DDP是一個(gè)客戶(hù)端和服務(wù)端之間的協(xié)議,他支持兩種操作:
- 由客戶(hù)端向服務(wù)端發(fā)起遠(yuǎn)程調(diào)用
- 客戶(hù)端訂閱數(shù)據(jù),在服務(wù)端數(shù)據(jù)變化時(shí),服務(wù)器保持向客戶(hù)端發(fā)起通知。
也就是說(shuō)客戶(hù)端只需要監(jiān)聽(tīng)(通過(guò) WebSocket 長(zhǎng)連接)服務(wù)端的數(shù)據(jù),當(dāng)服務(wù)端的 DB 發(fā)生數(shù)據(jù)變化的時(shí)候,就會(huì)通過(guò) DDP 將變化的數(shù)據(jù)返回給客戶(hù)端。
在 github 上找了一些資料和開(kāi)源庫(kù)。發(fā)現(xiàn)已經(jīng)有前輩提供了底層 iOS 設(shè)備與 meteor 服務(wù)端交互的庫(kù)。以下將會(huì)以 SwiftDDP 為例來(lái)分享一下,對(duì)她的使用和二次封裝。
正文
我們先來(lái)看一下 SwiftDDP 的目錄結(jié)構(gòu)
這里面最重要的文件是 Meteor.swift 和 DDPClient.swift。客戶(hù)端與服務(wù)端連接以及數(shù)據(jù)交互的主要邏輯都在這里。
二次封裝
對(duì)第三方庫(kù)進(jìn)行二次封裝的好處在于:
- 根據(jù)業(yè)務(wù)需要過(guò)濾不需要的接口
- 如果后期需要更換第三方庫(kù),可以減少對(duì)上層調(diào)用者的修改
以下是對(duì) SwiftDDP 進(jìn)行的簡(jiǎn)單封裝
/// MeteorWrapper.swift 暴露所有與 Meteor 相關(guān)的接口。對(duì)上層使用者來(lái)說(shuō)只需要知道這一個(gè)類(lèi)即可。
/// 在 AppDelegate 中調(diào)用 initMeteor(:)。需要注意在調(diào)用 login(:) 之前必須先 connectServer(:) ,且要保證連接成功
public typealias InitCollectionCallback = () -> ()
class MeteorWrapper {
// UI 界面需要實(shí)現(xiàn) ContentLoading protocol
var contentLoading: ContentLoading?
// 用于管理 subscribers
var subscriberLoader: SubscriberLoader = SubscriberLoader()
// 單例
class var shared: MeteorWrapper {
struct Static {
static let instance: MeteorWrapper = MeteorWrapper()
}
return Static.instance
}
func initMeteor(collections: InitCollectionCallback?) {
Meteor.client.allowSelfSignedSSL = false
Meteor.client.logLevel = .debug
NotificationCenter.default.addObserver(self, selector: #selector(ddpUserDidLogin), name: NSNotification.Name(rawValue: DDP_USER_DID_LOGIN), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(ddpUserDidLogout), name: NSNotification.Name(rawValue: DDP_USER_DID_LOGOUT), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(ddpWebSocketClose), name: NSNotification.Name(rawValue: DDP_WEBSOCKET_CLOSE), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(ddpWebSocketError), name: NSNotification.Name(rawValue: DDP_WEBSOCKET_ERROR), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(ddpDisconnected), name: NSNotification.Name(rawValue: DDP_DISCONNECTED), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(ddpFailed), name: NSNotification.Name(rawValue: DDP_FAILED), object: nil)
collections?()
}
open func connectServer(callback: DDPCallback? = nil) {
Meteor.connect(MeteorConfig.webSocketURL) {
self.contentLoading?.contentLoadingState = .connected
callback?()
}
}
open func login(callback: DDPMethodCallback?) {
guard let email = MeteorConfig.loginEmail, let password = MeteorConfig.loginPassword else {
return
}
Meteor.loginWithPassword(email, password: password, callback: callback)
}
open func login() {
guard let email = MeteorConfig.loginEmail, let password = MeteorConfig.loginPassword else {
return
}
Meteor.loginWithPassword(email, password: password)
}
open func logout(callback: DDPMethodCallback? = nil) {
Meteor.logout(callback)
}
open func getUserId() -> String? {
return Meteor.client.userId()
}
/**
獲取collection的results
*/
open func getCollectionRealm<T: MeteorDocumentRealm>(_ name: String, className: T.Type) -> Results<T> {
return (Meteor.collection(name) as! MeteorCollectionRealm<T>).getCollection()
}
// MARK: - Websocket/DDP connection failure events
@objc fileprivate func ddpUserDidLogin() {
}
@objc fileprivate func ddpUserDidLogout() {
}
@objc fileprivate func ddpWebSocketClose() {
contentLoading?.contentLoadingState = .websocket_close
}
@objc fileprivate func ddpWebSocketError() {
contentLoading?.contentLoadingState = .websocket_error
}
@objc fileprivate func ddpDisconnected() {
contentLoading?.contentLoadingState = .disconnected
}
@objc fileprivate func ddpFailed() {
contentLoading?.contentLoadingState = .failed
}
}
客戶(hù)端監(jiān)聽(tīng)器的封裝,向服務(wù)端發(fā)起監(jiān)聽(tīng)請(qǐng)求和清除監(jiān)聽(tīng)。
/// SubscriberLoader.swift
/*
SubscriberLoader 用于創(chuàng)建 collection 的監(jiān)聽(tīng)和管理
*/
class SubscriberLoader {
// store subscriber id
fileprivate var subscribers: [String] = []
func addSubscribers(_ withName: String, params: [Any]?, readyCallback: DDPCallback?) -> String?{
var ids:String? = nil
if let params = params {
ids = Meteor.subscribe(withName, params: params, callback: readyCallback)
} else {
ids = Meteor.subscribe(withName, callback: readyCallback)
}
guard ids != nil else {
return nil
}
subscribers.append(ids!)
return ids
}
func removeAllSubscribers() {
for id in subscribers {
Meteor.unsubscribe(withId: id)
}
}
func removeSubscriber(withName name: String) {
Meteor.unsubscribe(name, callback: nil)
}
func removeSubscriber(withId id: String) {
Meteor.unsubscribe(withId: id)
}
}
對(duì)應(yīng) DDP 的各種連接狀態(tài)。實(shí)現(xiàn) ContentLoading 協(xié)議,向上層通知 DDP 的狀態(tài)
// 用于存儲(chǔ) DDP WebSocket 狀態(tài),并且更新?tīng)顟B(tài)給 UI
protocol ContentLoading {
var contentLoadingState: ContentLoadingState { get set }
func loadContentIfNeeded()
}
enum ContentLoadingState: CustomStringConvertible {
case initial
case loading
case loaded
case error
case offline
case connected
case disconnected
case websocket_close
case websocket_error
case failed
var description: String {
switch self {
case .initial:
return "Initial"
case .loading:
return "Loading"
case .loaded:
return "Loaded"
case .error:
return "Error"
case .offline:
return "Offline"
case .connected:
return "Connected"
case .disconnected:
return "Disconnected"
case .websocket_close:
return "DDP Websocket Close"
case .websocket_error:
return "DDP Websocket Error"
case .failed:
return "DDP Failed"
}
}
}
如果你已經(jīng)了解過(guò) SwiftDDP 的使用方法,你一定知道她的數(shù)據(jù)都是存放在緩存里的。那如果需要將數(shù)據(jù)持久化到本地該如何呢?沒(méi)錯(cuò),那就需要重寫(xiě) MeteorDocument 和 MeteorCollection。
/// 與 MeteorDocument 基本一致,唯一的區(qū)別就是繼承了 RealmSwift 的 Object,并配置 _id 為 主鍵。
/// 她的使用方法和 MeteorDocument 也一樣。
/// 之所在字段前面加了下劃線,是因?yàn)樽约旱捻?xiàng)目中有一個(gè)字段和swift關(guān)鍵字產(chǎn)生沖突
class MeteorDocumentRealm: Object{
dynamic var _id:String = ""
open override class func primaryKey() -> String? {
return "_id"
}
// MARK: -- 借用 MeteorDecument 處理數(shù)據(jù)的方法
open func initData(id: String, fields: NSDictionary?) {
self._id = id
if let properties = fields {
for (key,value) in properties {
if !(value is NSNull) {
self.setValue(value, forKey: "_"+(key as! String))
}
}
}
}
open func update(_ fields: NSDictionary?, cleared: [String]?) {
if let properties = fields {
for (key,value) in properties {
print("Key: \(key), Value: \(value)")
self.setValue(value, forKey: "_"+(key as! String))
}
}
if let deletions = cleared {
for property in deletions {
self.setNilValueForKey("_"+property)
}
}
}
/*
Limitations to propertyNames:
- Returns an empty array for Objective-C objects
- Will not return computed properties, i.e.:
- If self is an instance of a class (vs., say, a struct), this doesn't report its superclass's properties, i.e.:
see http://stackoverflow.com/questions/24844681/list-of-classs-properties-in-swift
*/
func propertyNames() -> [String] {
return Mirror(reflecting: self).children.filter { $0.label != nil }.map { $0.label! }
}
/*
This method should be public so users of this library can override it for parsing their variables in their MeteorDocument object when having structs and such in their Document.
*/
open func fields() -> NSDictionary {
let fieldsDict = NSMutableDictionary()
let properties = propertyNames()
for name in properties {
if var value = self.value(forKey: name) {
if value as? Date != nil {
value = EJSON.convertToEJSONDate(value as! Date)
}
fieldsDict.setValue(value, forKey: name)
}
}
fieldsDict.setValue(self._id, forKey: "_id")
print("fields \(fieldsDict)")
return fieldsDict as NSDictionary
}
}
MeteorCollectionRealm 看起來(lái)就精簡(jiǎn)了很多。可能你會(huì)問(wèn)這里沒(méi)有了變更通知,上層該怎么知道數(shù)據(jù)發(fā)生了變化呢?因?yàn)槲覀冇昧?Realm。這里先留個(gè)懸念~~
class MeteorCollectionRealm<T: MeteorDocumentRealm>: AbstractCollection{
public override init(name: String) {
super.init(name: name)
}
/**
獲取 collection 的所有結(jié)果
*/
var realm: Realm?
open func getCollection() -> Results<T> {
if realm == nil {
realm = try! Realm()
}
return realm!.objects(T.self)
}
override func documentWasAdded(_ collection: String, id: String, fields: NSDictionary?) {
let document = T()
document.initData(id: id, fields: fields)
let realm = try? Realm()
try! realm?.write {
realm?.add(document, update: true)
}
}
override func documentWasChanged(_ collection: String, id: String, fields: NSDictionary?, cleared: [String]?) {
let realm = try? Realm()
let document = realm?.objects(T.self).filter(NSPredicate(format: "_id = %@", id))
if document != nil && (document?.count)! > 0 {
try! realm?.write {
document?.first?.update(fields, cleared: cleared)
realm?.add((document?.first)!, update: true)
}
}
}
override func documentWasRemoved(_ collection: String, id: String) {
let realm = try? Realm()
let document = realm?.objects(T.self).filter(NSPredicate(format: "_id = %@", id))
if document != nil && (document?.count)! > 0 {
try! realm?.write {
realm?.delete((document?.first)!)
}
}
}
// todo : insert 、update、 remove 等本地請(qǐng)求更新數(shù)據(jù)到服務(wù)器端的方法
}
基本的封裝做完了,接下來(lái)舉個(gè)例子來(lái)說(shuō)說(shuō)該怎么用吧。
/// AppDelegate.swift
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
...
// 初始化 MeteorWarper 組件
MeteorConfig.loginEmail = "robertzhangsh@gmail.com"
MeteorConfig.loginPassword = "password"
MeteorWrapper.shared.initMeteor {
// XXFields 繼承 MeteorDocumentRealm ,并遵循 Realm object 的構(gòu)建即可
_ = MeteorCollectionRealm<ThreadFields>(name: "threads")
_ = MeteorCollectionRealm<MessageFields>(name: "messages")
....
MeteorWrapper.shared.contentLoading = self
}
...
}
/// login.swift 登陸相關(guān)的操作類(lèi),當(dāng)然也可以根據(jù)具體的情況而定
// 登陸成功后的返回操作中
// meteor ddp
MeteorWrapper.shared.connectServer {
MeteorWrapper.shared.login() { (result , error) in
if error == nil {
let listsPage = 4
TSProgressHUD.ts_showWithStatus("加載數(shù)據(jù)中.....")
// 這里的參數(shù)是根據(jù)服務(wù)器需要給的,視情況而定
_ = MeteorWrapper.shared.subscriberLoader.addSubscribers("threads", params: [[:], ["limit":listsPage * 15,"sort":["lastMessageAt":-1]]], readyCallback: {
TSProgressHUD.ts_dismiss()
})
}
}
}
// 合適的地方注銷(xiāo)監(jiān)聽(tīng)
_ = MeteorWrapper.shared.subscriberLoader.removeSubscriber(withName: "threads")
封裝的思路
看完代碼后,終于要說(shuō)說(shuō)封裝的思路了。其實(shí)二次封裝沒(méi)什么可說(shuō)的,就是一個(gè)類(lèi)似 Helper 的單例類(lèi)。更有意思的地方應(yīng)該是 Realm 和 SwiftDDP 的結(jié)合。這種火花的摩擦很美妙,讓人欲罷不能。
我們將業(yè)務(wù)劃分成兩個(gè)方面,一個(gè)是寫(xiě)(通過(guò) Meteor DPP 獲取服務(wù)端的數(shù)據(jù),并將之寫(xiě)入數(shù)據(jù)庫(kù)),另一個(gè)是讀(上層展示只需要讀取數(shù)據(jù)庫(kù),不關(guān)心數(shù)據(jù)怎么來(lái)的)。寫(xiě)和讀是獨(dú)立的相互之間并不關(guān)心。她們只關(guān)注自己對(duì)數(shù)據(jù)庫(kù)的操作。對(duì)于上層展示,Realm天生提供了數(shù)據(jù)更新的解決方案,一切都變的如此簡(jiǎn)單。這讓人想起 Android 中的 ContentProvider。內(nèi)容提供者不會(huì)關(guān)心誰(shuí)用了數(shù)據(jù),她只關(guān)注數(shù)據(jù)的存儲(chǔ)和數(shù)據(jù)更新后的廣播通知。任務(wù)分離后,寫(xiě)和讀也就隔離開(kāi)來(lái)。
MeteorCollectionRealm 的角色就是寫(xiě)入者,代碼也很簡(jiǎn)單。唯一的問(wèn)題就是要注意 Realm 操作線程的問(wèn)題。
最后
項(xiàng)目結(jié)構(gòu)的設(shè)計(jì)是一件很有意思的事情,不同的人有不同的方法和技巧。殊途同歸都是為了能更清晰的劃分結(jié)構(gòu)。
ps:最近狀態(tài)不佳,寫(xiě)的有點(diǎn)亂。