iOS Deep Linking 最佳实践

在 iOS 中,deep linking 实际上包括 URL Scheme、Universal Link、notification 或者 3D Touch 等 URL 跳转方式。应用场景比如常见的通知,社交分享,支付,或者在 webView 中点击特定链接在 app 中打开并跳转到对应的原生页面。

用的最多也是最常用的是通过 Custom URL Scheme 来实现 deep linking。在 application:openURL:sourceApplication:annotation 或者 iOS9 之后引入的 application:openURL:options 中,通过对 URL 进行处理来执行相应的业务逻辑。一般地简单地通过字符串比较就可以了。但如果 URL 跳转的对应场景比较多,开发维护起来就不那么简单了。对此的最佳实践是引入 router 来统一可能存在的所有入口。

这里介绍的一种使用 router 来组织入口的方法是来自与 kickstarter-ios 这个开源项目,是纯 swift 开发的,而且在 talk.objc.io 上有开发者的视频分享

在工程,通过定于 Navigation enum,把所有支持通过 URL 跳转的 entry point 都定义成一个 case。

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 返回

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,使得代码具有了很高的可读性,非常清晰明了。

    原文作者:babyface91
    原文地址: https://segmentfault.com/a/1190000012656454
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞