在 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