在 iOS 中,deep linking 实际上包括 URL Scheme、Universal Link、notification 或者 3D Touch 等 URL 跳转方式。应用场景好比常见的通知,社交分享,支付,或者在 webView 中点击特定连接在 app 中打开并跳转到对应的原生页面。ios
用的最多也是最经常使用的是经过 Custom URL Scheme 来实现 deep linking。在 application:openURL:sourceApplication:annotation
或者 iOS9 以后引入的 application:openURL:options
中,经过对 URL 进行处理来执行相应的业务逻辑。通常地简单地经过字符串比较就能够了。但若是 URL 跳转的对应场景比较多,开发维护起来就不那么简单了。对此的最佳实践是引入 router 来统一可能存在的全部入口。web
这里介绍的一种使用 router 来组织入口的方法是来自与 kickstarter-ios 这个开源项目,是纯 swift 开发的,并且在 talk.objc.io 上有开发者的视频分享。swift
在工程,经过定于 Navigation enum,把全部支持经过 URL 跳转的 entry point 都定义成一个 case。app
public enum Navigation { case checkout(Int, Navigation.Checkout) case messages(messageThreadId: Int) case tab(Tab) ... }
在 allRoutes 字典中列出了全部的 URL 模板,以及与之对应的解析函数。函数
private let allRoutes: [String: (RouteParams) -> Decode<Navigation>] = [ "/mpss/:a/:b/:c/:d/:e/:f/:g": emailLink, "/checkouts/:checkout_param/payments": paymentsRoot, "/discover/categories/:category_id": discovery, "/projects/:creator_param/:project_param/comments": projectComments, ... ]
在 match(_ url: URL) -> Navigation
函数中经过遍历 allRoutes,去匹配传入的 url。具体过程是:在 match
函数内,调用 parsedParams(_ url: URL, fromTemplate: template: String) -> [String: RouteParams]
函数,将分割后 template 字符串做 key,取出 url 中的对应的 value,并组装成 [String: RouteParams]
字典返回。最后将返回的字典 flatmap(route)
,即传入对应的解析函数,最终获得 Navigation
返回url
public static func match(_ url: URL) -> Navigation? { return allRoutes.reduce(nil) { accum, templateAndRoute in let (template, route) = templateAndRoute return accum ?? parsedParams(url: url, fromTemplate: template).flatMap(route)?.value } }
private func parsedParams(url: URL, fromTemplate template: String) -> RouteParams? { ... let templateComponents = template .components(separatedBy: "/") .filter { $0 != "" } let urlComponents = url .path .components(separatedBy: "/") .filter { $0 != "" && !$0.hasPrefix("?") } guard templateComponents.count == urlComponents.count else { return nil } var params: [String: String] = [:] for (templateComponent, urlComponent) in zip(templateComponents, urlComponents) { if templateComponent.hasPrefix(":") { // matched a token let paramName = String(templateComponent.characters.dropFirst()) params[paramName] = urlComponent } else if templateComponent != urlComponent { return nil } } URLComponents(url: url, resolvingAgainstBaseURL: false)? .queryItems? .forEach { item in params[item.name] = item.value } var object: [String: RouteParams] = [:] params.forEach { key, value in object[key] = .string(value) } return .object(object) }
经过 Navigation enum,把一个 deep link 方式传入的 URL,解析成一个 Navigation 的 case,使得代码具备了很高的可读性,很是清晰明了。code