路由 0.0.1

路由 0.0.1

Min Kim 维护。



路由 0.0.1

路由🗺

Build Status CocoaPods Compatible Carthage Compatible

这个库是流行的Objective-C库JLRoutes的Swift端移植/分支。许多❤️归功于joeldev创建了这样一个令人愉悦的路由库。

Routes是一个纯Swift URL路由库,具有简单的基于块API。它旨在使用最少的代码轻松处理应用中的复杂URL模式。

安装

Carthage (推荐)

Routes 添加到您的 Cartfile

github "min/Routes"

CocoaPods

Routes 添加到您的 Podfile

pod 'Routes'

需求

  • 支持 iOS 9.0+ / tvOS 9.0+ / watchOS 2.0+
  • Swift 4.2

入门

在 Info.plist 中配置你的 URL 方案。

class AppDelegate: UIResponder, UIApplicationDelegate {
    let router: Router = Router()
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        router.default.add(pattern: "/user/view/:user_id") { parameters in
            let userId = parameters["user_id"]
            
            // present UI for viewing user with userId
        }
        return true
    }
    
    func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
        return router.route(to: url)
    }
}

添加 /user/view/:user_id 路由后,以下调用将导致处理程序块被调用,并带有包含 {"user_id": "min"} 的字典。

router.route(resource: "myapp://user/view/min")

处理程序块链式调用

处理程序块预计会返回一个布尔值,以表示是否已处理路由。如果块返回 false,Routes 将表现得像该路由不匹配一样,并且它将继续寻找匹配项。只有当模式字符串匹配并且块返回 true 时,才认为路由匹配。

另外,请注意,如果您为处理程序块传递 nil,则会创建一个内部处理程序块,该块简单地返回 true

方案

Routes 支持在特定的 URL 方案内设置路由。设置在方案内的路由只能由使用匹配 URL 方案进行匹配的 URL 匹配。默认情况下,所有路由都进入全局方案。

let router = Router()

router.default["foo"] = { parameters in
    // This block is called if the scheme is not 'thing' or 'stuff' (see below)	
    return true
}

router["thing"]["foo"] = { parameters in
    // This block is called for thing://foo
    return true
}

router["stuff"]["foo"] = { parameters in
    // This block is called for stuff://foo
    return true
}

以下示例显示您可以在不同的方案中声明相同的路由,并根据每个方案使用不同的回调进行处理。

继续使用此示例,如果您添加以下路由

router.default["/global"] = { parameters in
    return true
}

然后尝试路由 URL thing://global,则不会匹配,因为这路由未经在 thing 方案中声明,而是在全局方案(我们假设这是开发者想要的)中声明。但是,您可以很容易地通过将以下属性设置为 true 来更改此行为

router["thing"].shouldFallback = true

这告诉路由器,如果无法在thing方案(即,以thing:开头但没有找到合适的路由)内路由URL,则尝试通过在全球路由器方案中寻找匹配的路由来恢复。在将该属性设置为true后,URL thing://global将被路由到/global处理程序块。

通配符

路由器支持设置路由,使其匹配被路由URL末尾的任意数量的路径组件。包含额外路径组件的数组将以键Definition.Keys.wildcard添加到参数字典中。

例如,以下路由将针对以/wildcard/开头的任何URL触发,但如果下一个组件不是joker,则处理程序将拒绝它。

router.default.add(pattern: "/wildcard/*") { parameters in
    let components = parameters[Definition.Keys.wildcard]

    guard let component = components.first, component == "joker" else {
        return false
    }

    return true
}

可选路由

路由器支持设置带可选参数的路由。在路由注册时刻,路由器将注册包含所有带可选参数和无可选参数的路由组合的多个路由。例如,对于路由/the(/foo/:a)(/bar/:b),它将注册以下路由

  • /the/foo/:a/bar/:b
  • /the/foo/:a
  • /the/bar/:b
  • /the

许可协议

MIT。有关详细信息,请参阅LICENSE文件。