應用
- 集成
pod 'URLNavigator'
- 創建
NavigationMap
文件 - 將視圖註冊到URL模式
navigator.register("petrel://douban") { url, values, context in
return DouBanViewController()
}
- 在
didFinishLaunchingWithOptions
方法中初始化
URLNavigationMap.initialize(navigator: navigator)
- 跳轉
navigator.push("petrel://douban")
源碼解析
註冊過程就是通俗的說就是將製造器工廠(ViewControllerFactory
,URLOpenHandlerFactory
)以URL爲key存到字典(viewControllerFactories
,handlerFactories
)中, 跳轉過程 先用URLMatcher
解析URL,然後映射控制器工廠,生成控制器,跳轉並返回控制器
註冊
註冊方式有兩種:register,handle
- register
func register(_ pattern: URLPattern, _ factory: @escaping ViewControllerFactory)
register 是直接註冊ViewController的生產工廠,對應跳轉方式:push,present
- handle
func handle(_ pattern: URLPattern, _ factory: @escaping URLOpenHandlerFactory)
handle可以理解爲自定義的操作工廠,比如彈框,或吐絲,對應跳轉方式:open
跳轉
URLNavigator的跳轉方式有三種:push,present,open
- push
public func push(_ url: URLConvertible, context: Any? = nil, from: UINavigationControllerType? = nil, animated: Bool = true) -> UIViewController?
public func push(_ viewController: UIViewController, from: UINavigationControllerType? = nil, animated: Bool = true) -> UIViewController?
push時可以直接給出要跳轉的ViewController,設置from從哪個界面跳轉,不設置默認從當前控制器跳轉,也可以通過url,去跳轉,使用url跳轉時可以設置context,
- present
public func present(_ url: URLConvertible, context: Any? = nil, wrap: UINavigationController.Type? = nil, from: UIViewControllerType? = nil, animated: Bool = true, completion: (() -> Void)? = nil) -> UIViewController?
public func present(_ viewController: UIViewController, wrap: UINavigationController.Type? = nil, from: UIViewControllerType? = nil, animated: Bool = true, completion: (() -> Void)? = nil) -> UIViewController?
present比push多出兩個參數 wrap:可以在要跳轉的ViewController上包裹一層,比如在ViewController上包裹一層navigationcontroller,completion結束後可做操作,其餘參數和push的作用一致
- open
func open(_ url: URLConvertible, context: Any? = nil) -> Bool
跳轉自定義操作,可以設置context
URLMatcher
還沒有理解太透徹,稍後理解透徹了再補充上