iOS Deep Linking 最佳實踐

babyface91發表於2017-12-31

在 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,使得程式碼具有了很高的可讀性,非常清晰明瞭。

相關文章