中文文档

ReerRouter

用于 iOS 的 App URL 路由(仅限 Swift)。灵感来源于 URLNavigator

Swift 5.10 及更高版本支持 @_used@_section,允许将数据写入 section。结合 Swift Macros,这实现了类似于 Objective-C 时代各种解耦和注册信息方法的功能。本框架也支持以这种方式注册路由。

注册 UIViewController

extension Route.Key {
    // Note: The variable name 'chat' must exactly match the assigned string
    static let chat: Route.Key = "chat"
}

@Routable(.chat)
class ChatViewController: UIViewController {
    static func make(with param: Route.Param) -> ChatViewController? {
        return .init()
    }

    // ... other methods ...
}

@Routable("setting")
class SettingViewController: UIViewController {
    static func make(with param: Route.Param) -> SettingViewController? {
        return .init()
    }

    // ... other methods ...
}

注册 action

extension Route.Key {
    // Note: The variable name 'testKey' must exactly match the assigned string
    static let testKey: Self = "testKey"
}

struct Foo {
    #route(key: .testKey, action: { params in
        print("testKey triggered nested")
    })
}

🟡 当前,@_used@_section 功能在 Swift 中仍为实验性特性,需要通过配置设置启用。请参考集成文档了解详情。

示例 App

要运行示例项目,请克隆 repo,并首先从 Example 目录运行 pod install

要求

XCode 16.0 +

iOS 13 +

Swift 5.10

swift-syntax 600.0.0

安装

CocoaPods

ReerRouter 可通过 CocoaPods 获得。要安装它,只需将以下行添加到您的 Podfile

pod 'ReerRouter'

由于 CocoaPods 不直接支持使用 Swift Macros,宏实现可以编译成二进制文件使用。集成方法如下。需要在依赖路由器的组件中设置 s.pod_target_xcconfig,以加载宏实现的二进制插件

s.pod_target_xcconfig = {
    'OTHER_SWIFT_FLAGS' => '-enable-experimental-feature SymbolLinkageMarkers -Xfrontend -load-plugin-executable -Xfrontend ${PODS_ROOT}/ReerRouter/Sources/Resources/ReerRouterMacros#ReerRouterMacros'
  }
  
  s.user_target_xcconfig = {
    'OTHER_SWIFT_FLAGS' => '-enable-experimental-feature SymbolLinkageMarkers -Xfrontend -load-plugin-executable -Xfrontend ${PODS_ROOT}/ReerRouter/Sources/Resources/ReerRouterMacros#ReerRouterMacros'
  }

或者,如果不使用 s.pod_target_xcconfig,您可以将以下脚本添加到 Podfile 中进行统一处理

post_install do |installer|
  installer.pods_project.targets.each do |target|
    rhea_dependency = target.dependencies.find { |d| ['ReerRouter'].include?(d.name) }
    if rhea_dependency
      puts "Adding Rhea Swift flags to target: #{target.name}"
      target.build_configurations.each do |config|
        swift_flags = config.build_settings['OTHER_SWIFT_FLAGS'] ||= ['$(inherited)']
        
        plugin_flag = '-Xfrontend -load-plugin-executable -Xfrontend ${PODS_ROOT}/ReerRouter/Sources/Resources/ReerRouterMacros#ReerRouterMacros'
        
        unless swift_flags.join(' ').include?(plugin_flag)
          swift_flags.concat(plugin_flag.split)
        end

        # Add experimental feature flag for SymbolLinkageMarkers
        symbol_linkage_flag = '-enable-experimental-feature SymbolLinkageMarkers'

        unless swift_flags.join(' ').include?(symbol_linkage_flag)
          swift_flags.concat(symbol_linkage_flag.split)
        end

        config.build_settings['OTHER_SWIFT_FLAGS'] = swift_flags
      end
    end
  end
end

Swift Package Manager

对于需要依赖 ReerRouter 的包,需要启用 Swift 实验性特性

// Package.swift
let package = Package(
    name: "APackageDependOnReerRouter",
    platforms: [.iOS(.v13)],
    products: [
        .library(name: "APackageDependOnReerRouter", targets: ["APackageDependOnReerRouter"]),
    ],
    dependencies: [
        .package(url: "https://github.com/reers/ReerRouter.git", from: "2.2.3")
    ],
    targets: [
        .target(
            name: "APackageDependOnReerRouter",
            dependencies: [
                .product(name: "ReerRouter", package: "ReerRouter")
            ],
            // Add here to enable the experimental feature
            swiftSettings:[.enableExperimentalFeature("SymbolLinkageMarkers")]
        ),
    ]
)

在主 App Target 的 Build Settings 中,设置为启用实验性特性:-enable-experimental-feature SymbolLinkageMarkers CleanShot 2024-10-12 at 20 39 59@2x

开始使用

1. 理解 Route.Key

Route.Key 有两种模式。

模式 1:Route.Key 指的是 URL 的 host + path

/// myapp://example.com/over/there?name=phoenix#nose
/// \______/\_________/\_________/ \__________/ \__/
///    |         |          |           |        |
///  scheme     host       path      queries   fragment
///              \_________/
///                   |
///               route key

模式 1:为路由器实例设置 host 并使用 path 作为 Route.Key

/// myapp://example.com/over/there?name=phoenix#nose
/// \______/\_________/\_________/ \__________/ \__/
///    |         |          |           |        |
///  scheme     host       path      queries   fragment
///                         |
///                         |
///                    route key

您可以通过实现 RouterConfigable 协议来配置为模式 2

extension Router: RouterConfigable {
    public static var host: String {
        return "example.com"
    }
}

2. 注册路由

模式 1

现在 Route.Key 指的是 url 的 hostpath 的组合。

Router.shared.registerAction(with: "abc_action") { _ in
    print("action executed.")
}
extension Route.Key {
    static let userPage: Self = "user"
}
Router.shared.register(UserViewController.self, forKey: .userPage)
Router.shared.register(UserViewController.self, forKey: "user")
Router.shared.registerPageClasses(with: ["preference": PreferenceViewController.self])
Router.shared.registerPageClasses(with: ["preference": "ReerRouter_Example.PreferenceViewController"])
extension Route.Key {
    static let testKey: Self = "testKey"
}

struct Foo {
    #route(key: .testKey, action: { params in
        print("testKey triggered nested")
    })
}
extension Route.Key {
    static let chat: Route.Key = "chat"
}

@Routable(.chat)
class ChatViewController: UIViewController {
    static func make(with param: Route.Param) -> ChatViewController? {
        return .init()
    }

    // ... other methods ...
}

@Routable("setting")
class SettingViewController: UIViewController {
    static func make(with param: Route.Param) -> SettingViewController? {
        return .init()
    }

    // ... other methods ...
}

模式 2

首先,您应该为路由器实例设置 host

Router.shared.host = "phoenix.com"

现在 Route.Key 指的是 url 路径,然后所有的注册方法都与 模式 1 相同。(“path”,“/path” 都支持。)

class UserViewController: UIViewController, Routable {
    var params: [String: Any]
    
    init(params: [String: Any]) {
        self.params = params
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    static func make(with param: Route.Param) -> UserViewController? {
        return .init(params: param.allParams)
    }
}   

3. 执行一个路由 action。

Router.shared.executeAction(byKey: "abc_action")

// Mode 1.
Router.shared.open("myapp://abc_action")

// Mode 2.
Router.shared.open("myapp://phoenix.com/abc_action")

4. 打开一个视图控制器。

Router.shared.present(byKey: .userPage, embedIn: UINavigationController.self, userInfo: [
    "name": "apple",
    "id": "123123"
])

// Mode 1.
Router.shared.open("myapp://user?name=phoenix")
Router.shared.push("myapp://user?name=phoenix")
Router.shared.present("myapp://user?name=phoenix")

// Mode 2.
Router.shared.open("myapp://phoenix.com/user?name=phoenix")
Router.shared.push("myapp://phoenix.com/user?name=phoenix")
Router.shared.present("myapp://phoenix.com/user?name=phoenix")

5. 关于路由的 App 委托。

extension RouteManager: RouterDelegate {
    func router(_ router: Router, willOpenURL url: URL, userInfo: [String : Any]) -> URL? {
        print("will open \(url)")
        if let _ = url.absoluteString.range(of: "google") {
            return URL(string: url.absoluteString + "&extra1=234244&extra2=afsfafasd")
        } else if let _ = url.absoluteString.range(of: "bytedance"), !isUserLoggedIn() {
            print("intercepted by delegate")
            return nil
        }
        return url
    }

    func router(_ router: Router, didOpenURL url: URL, userInfo: [String : Any]) {
        print("did open \(url) success")
    }
    
    func router(_ router: Router, didFailToOpenURL url: URL, userInfo: [String : Any]) {
        print("did fail to open \(url)")
    }
    
    func router(_ router: Router, didFallbackToURL url: URL, userInfo: [String: Any]) {
        print("did fallback to \(url)")
    }
}

6. Fallback

Router.shared.open("myapp://unregisteredKey?route_fallback_url=myapp%3A%2F%2Fuser%3Fname%3Di_am_fallback")

7. Redirect

class PreferenceViewController: UIViewController, Routable {
    static func make(with param: Route.Param) -> PreferenceViewController? {
        return .init()
    }
    
    class func redirectURLWithRouteParam(_ param: Route.Param) -> URL? {
        if let value = param.allParams["some_key"] as? String, value == "redirect" {
            return URL(string: "myapp://new_preference")
        }
        return nil
    }
}

8. 路由器单例的全局实例。

public let AppRouter = Router.shared
AppRouter.open("myapp://user")

9. 即将打开和已打开时的通知。

NotificationCenter.default.addObserver(
    forName: Notification.Name.routeWillOpenURL,
    object: nil,
    queue: .main
) { notification in
    if let param = notification.userInfo?[Route.notificationUserInfoKey] as? Route.Param {
        print("notification: route will open \(param.sourceURL)")
    }
}

NotificationCenter.default.addObserver(
    forName: Notification.Name.routeDidOpenURL,
    object: nil,
    queue: .main
) { notification in
    if let param = notification.userInfo?[Route.notificationUserInfoKey] as? Route.Param {
        print("notification: route did open \(param.sourceURL)")
    }
}

10. 自定义控制转场。

public typealias UserTransition = (
    _ fromNavigationController: UINavigationController?,
    _ fromViewController: UIViewController?,
    _ toViewController: UIViewController
) -> Bool

public enum TransitionExecutor {
    /// Transition will be handled by router automatically.
    case router
    /// Transition will be handled by user who invoke the router `push` or `present` method.
    case user(UserTransition)
    /// Transition will be handled by user who invoke the router `push` or `present` method.
    case delegate
}

let transition: Route.UserTransition = { fromNavigationController, fromViewController, toViewController in
    toViewController.transitioningDelegate = self.animator
    toViewController.modalPresentationStyle = .currentContext
    // Use the router found view controller directly, or just handle transition by yourself.
    // fromViewController?.present(toViewController, animated: true)
    self.present(toViewController, animated: true)
    return true
}
AppRouter.present(user.urlString, transitionExecutor: .user(transition))

11. UIViewController 的打开样式。

路由器打开控制器的优先级顺序如下

`Router` instance property `preferredOpenStyle` <
  `Routable` property `preferredOpenStyle` that UIViewController implemented <
    The method you called. If you called `Router.push(...)`, the view controller will be pushed.

12. 禁止转场动画。

Router.shared.open("myapp://user?name=google&route_no_animation=1")

13. 外部拦截。

在某些特殊场景中拦截路由,返回 false 表示拦截该 url。

Router.shared.addInterceptor(forKey: .userPage) { (_) -> Bool in
    print("intercepted user page")
    return true
}

Router.shared.addInterceptor(forKey: .userPage) { (params) -> Bool in
    print("intercepted user page")
    if let name = params.allParams["name"] as? String, name == "google" {
        print("intercepted user page success")
        return false
    }
    return true
}

14. 自定义检索在 section 中注册的路由的时机

extension Router: RouterConfigable {
    // This configuration disables automatic retrieval
    public static var registrationMode: RegistrationMode { return .manual }
}
// Then call at an appropriate time
Router.shared.registerRoutes()

作者

phoenix, x.rhythm@qq.com

许可证

ReerRouter 基于 MIT 许可证可用。有关更多信息,请参见 LICENSE 文件。