ios swift URLNavigator 路由 的使用

ios swift URLNavigator 路由 的使用

路由可以很大程度的对项目模块进行解耦;页面跳转有很多不确定性,用路由最合适不过了,URLNavigator是swift 路由的开源库,特别是推广,链接跳转等

URLNavigator库地址:https://github.com/devxoul/URLNavigator
我写了个小demo 用 URLNavigator 路由跳转

1.注册Url

self.navigator.register(RouterMap.play_key) { _, _, _ in
            PlayViewController()
        }

2.从注册的url里得到对应的Viewcontroller

let vc = navigator.viewController(for: link)

注意 navigator应该是同意个对象,可设置项目全局变量 如 Appdellegate

3.参数

URLNavigator 只能传一个参数 ,如果是多参数呢?
多参数 可以把参数转成json 传入,然后再解析json 成参数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/") { _, 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.调用方式

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)
       }

6.惯例,附上demo 地址

demo地址:https://gitee.com/Sunny0123/swift-router-demo

你可能感兴趣的:(ios swift URLNavigator 路由 的使用)