public class JTRouterManager { private var moduleServices: [JTRouterProtocol] = [] public static let shared = JTRouterManager() private init() {} public func registService(service: JTRouterProtocol) { let isRegisted = moduleServices.contains { value in return value.identifier == service.identifier } if !isRegisted { moduleServices.append(service) } } @discardableResult public func handle(routerEvent: JTRouterModuleEventProtocol, completion: (([String: Any]) -> Void)?) -> Bool { var temp: JTRouterProtocol? for service in moduleServices { if service.canHandle(routerEvent: routerEvent) { temp = service break } } guard let handler = temp else { return false } return handler.handle(routerEvent: routerEvent, completion: completion) } }
使用示例
定义模块内事件
1 2 3 4 5 6 7
/// 登录模块,对外暴露的接口 public enum JTLoginModuleRouterEvent: JTRouterModuleEventProtocol { /// 打开登录页面 case openLoginVC /// 根据用户id获取用户信息 case getInfo(uid: String) }
public class JTLoginModuleRouterService: NSObject, JTRouterProtocol { @objc public class func serverStart() { JTLoginModuleRouterService.shared } public static let shared = JTLoginModuleRouterService() public override init() { super.init() JTRouterManager.shared.registService(service: self) } }
public extension JTLoginModuleRouterService { public var identifier: String { return String(describing: self) } public func canHandle(routerEvent: JTRouterModuleEventProtocol) -> Bool { return routerEvent is JTLoginModuleRouterEvent } @discardableResult public func handle(routerEvent: JTRouterModuleEventProtocol, completion: (([String: Any]) -> Void)?) -> Bool { guard let loginRouter = routerEvent as? JTLoginModuleRouterEvent else { return false }
switch loginRouter { case .openLoginVC: handleOpenLoginVC() case .getInfo(let uid): let callbackInfo = handleGetInfo(uid: uid) completion?(callbackInfo) } return true } }
private extension JTLoginModuleRouterService { private func handleOpenLoginVC() { let vc = JTLoginMainViewController() // do something } private func handleGetInfo(uid: String) -> [String: Any] { // get infos let result: [String: Any] = ["name": "jt"] return result } }
外部调用示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14
let routerEvent1 = JTLoginModuleRouterEvent.openLoginVC
JTRouterManager.shared.handle(routerEvent: routerEvent1) { info in // do something with call back info }
let routerEvent2 = JTLoginModuleRouterEvent.getInfo(uid: "id")
JTRouterManager.shared.handle(routerEvent: routerEvent2) { info in // do something with call back info // ["name": "jt"] }
补充
因为模块内需要在项目启动时,注册自身路由服务到路由管理中心。但是,在 Swift 中 +(void)load 方法不能使用,这里还是使用了 OC 的类来进行协助。