ios swift URLNavigator 路由 的使用
路由可以很大程度的對項目模塊進行解耦措嵌;頁面跳轉(zhuǎn)有很多不確定性同眯,用路由最合適不過了,URLNavigator是swift 路由的開源庫氏义,特別是推廣锌俱,鏈接跳轉(zhuǎn)等
URLNavigator庫地址:https://github.com/devxoul/URLNavigator
我寫了個小demo 用 URLNavigator 路由跳轉(zhuǎn)
1.注冊Url
self.navigator.register(RouterMap.play_key) { _, _, _ in
PlayViewController()
}
2.從注冊的url里得到對應(yīng)的Viewcontroller
let vc = navigator.viewController(for: link)
注意 navigator應(yīng)該是同意個對象禽额,可設(shè)置項目全局變量 如 Appdellegate
3.參數(shù)
URLNavigator 只能傳一個參數(shù) 孽糖,如果是多參數(shù)呢钙蒙?
多參數(shù) 可以把參數(shù)轉(zhuǎn)成json 傳入福扬,然后再解析json 成參數(shù)Model
4.RouterMap 源碼
//
// RouterMap.swift
// RouterDemo
//
// Created by lizhi on 2022/2/24.
//
import UIKit
import URLNavigator
protocol ConvertToStringable: Codable {
func toJsonString() -> String
}
extension ConvertToStringable {
func toString() -> String {
let data = try? JSONEncoder().encode(self)
guard let da = data else { return "" }
guard let st = String(data: da, encoding: .utf8) else { return "" }
return st
}
}
struct RouterUserInfo: Codable {
var userID: Int
var name: String
}
extension RouterUserInfo: ConvertToStringable {
func toJsonString() -> String {
return self.toString()
}
}
enum RouterKey {
case User_Key(param: RouterUserInfo)
}
class RouterMap: NSObject {
static let shared = RouterMap()
lazy var navigator = Navigator()
static let user_key = "myapp://user/"
static let play_key = "myapp://play"
func registerURLs() {
self.navigator.register("myapp://user/<mine>") { _, values, _ in
guard let json = values["mine"] as? String else { return nil }
let userInfo = json.toObject(RouterUserInfo.self)
return UserViewController(param: userInfo)
}
self.navigator.register(RouterMap.play_key) { _, _, _ in
PlayViewController()
}
}
class func controller(for key: RouterKey) -> UIViewController? {
var link = ""
switch key {
case .User_Key(let param):
link = RouterMap.user_key + param.toJsonString()
}
let vc = RouterMap.shared.navigator.viewController(for: link)
return vc
}
}
5.調(diào)用方式
let userInfo = RouterUserInfo(userID: 11, name: "用戶名稱")
let key = RouterKey.User_Key(param: userInfo)
let vc = RouterMap.controller(for: key)
if vc != nil {
self.navigationController?.pushViewController(vc!, animated: true)
}