⛵️ URLNavigator provides an elegant way to navigate through view controllers by URLs. URL patterns can be mapped by using URLNavigator.register(_:_:) function.
URLNavigator can be used for mapping URL patterns with 2 kind of types: URLNavigable and URLOpenHandler. URLNavigable is a type which defines an custom initializer and URLOpenHandler is a closure which can be executed. Both an initializer and a closure receive an URL and placeholder values.
URL patterns can contain placeholders. Placeholders will be replaced with matching values from URLs. Use < and > to make placeholders. Placeholders can have types: string(default), int, float, and path.
For example, myapp://user/<int:id> matches with:
myapp://user/123myapp://user/87
But it doesn't match with:
myapp://user/devxoul(expected int)myapp://user/123/posts(different url structure)/user/devxoul(missing scheme)
URLNavigator allows to map view controllers and URL open handlers with URL patterns. Here's an example of mapping URL patterns with view controllers and a closure. Each closures has three parameters: url, values and context.
urlis an URL that is passed frompush()andpresent().valuesis a dictionary that contains URL placeholder keys and values.contextis a dictionary which contains extra values passed frompush(),present()oropen().
letnavigator=Navigator()
// register view controllers
navigator.register("myapp://user/<int:id>"){ url, values, context inguardlet userID =values["id"]as?Intelse{returnnil}returnUserViewController(userID: userID)}
navigator.register("myapp://post/<title>"){ url, values, context inreturn storyboard.instantiateViewController(withIdentifier:"PostViewController")}
// register url open handlers
navigator.handle("myapp://alert"){ url, values, context inlettitle= url.queryParameters["title"]letmessage= url.queryParameters["message"]presentAlertController(title: title, message: message)returntrue}URLNavigator can push and present view controllers and execute closures with URLs.
Provide the from parameter to push() to specify the navigation controller which the new view controller will be pushed. Similarly, provide the from parameter to present() to specify the view controller which the new view controller will be presented. If the nil is passed, which is a default value, current application's top most view controller will be used to push or present view controllers.
present() takes an extra parameter: wrap. If a UINavigationController class is specified, the new view controller will be wrapped with the class. Default value is nil.
Navigator.push("myapp://user/123")Navigator.present("myapp://post/54321", wrap:UINavigationController.self)Navigator.open("myapp://alert?title=Hello&message=World")URLNavigator officially supports CocoaPods only.
Podfile
pod'URLNavigator'You can find an example app here.
- Build and install the example app.
- Open Safari app
- Enter
navigator://user/devxoulin the URL bar. - The example app will be launched.
Define as a global constant:
letnavigator=Navigator()classAppDelegate:UIResponder,UIApplicationDelegate{ // ... }
Register to an IoC container:
container.register(NavigatorProtocol.self){ _ inNavigator()} // Swinject letnavigator= container.resolve(NavigatorProtocol.self)!
Inject dependency from a composition root.
I'd prefer using separated URL map file.
structURLNavigationMap{staticfunc initialize(navigator:NavigatorProtocol){
navigator.register("myapp://user/<int:id>"){...}
navigator.register("myapp://post/<title>"){...}
navigator.handle("myapp://alert"){...}}}Then call initialize() at AppDelegate's application:didFinishLaunchingWithOptions:.
@UIApplicationMainfinalclassAppDelegate:UIResponder,UIApplicationDelegate{func application(
_ application:UIApplication,
didFinishLaunchingWithOptions launchOptions:[UIApplicationLaunchOptionsKey:Any]?)->Bool{
// Navigator
URLNavigationMap.initialize(navigator: navigator)
// Do something else...
}}It's available to open your app with URLs if custom schemes are registered. In order to navigate to view controllers with URLs, you'll have to implement application:didFinishLaunchingWithOptions: method.
func application(
_ application:UIApplication,
didFinishLaunchingWithOptions launchOptions:[UIApplicationLaunchOptionsKey:Any]?)->Bool{
// ...
if let url =launchOptions?[.url]as?URL{
if let opened = navigator.open(url)if !opened {
navigator.present(url)}}returntrue}You'll might want to implement custom URL open handler. Here's an example of using URLNavigator with other URL open handlers.
func application(_ application:UIApplication, open url:URL, sourceApplication:String?, annotation:Any)->Bool{
// If you're using Facebook SDK
letfb=FBSDKApplicationDelegate.sharedInstance()if fb.application(application, open: url, sourceApplication: sourceApplication, annotation: annotation){returntrue}
// URLNavigator Handler
if navigator.open(url){returntrue}
// URLNavigator View Controller
if navigator.present(url, wrap:UINavigationController.self)!=nil{returntrue}returnfalse}letcontext:[AnyHashable:Any]=["fromViewController":self]Navigator.push("myapp://user/10", context: context)Navigator.present("myapp://user/10", context: context)Navigator.open("myapp://alert?title=Hi", context: context)You can define custom URL Value Converters for URL placeholders.
For example, the placeholder <region> is only allowed for the strings ["us-west-1", "ap-northeast-2", "eu-west-3"]. If it doesn't contain any of these, the URL pattern should not match.
Add a custom value converter to the [String: URLValueConverter] dictionary on your instance of Navigator.
navigator.matcher.valueConverters["region"]={ pathComponents, index inletallowedRegions=["us-west-1","ap-northeast-2","eu-west-3"]if allowedRegions.contains(pathComponents[index]){returnpathComponents[index]}else{returnnil}}With the code above, for example, myapp://region/<region:_> matches with:
myapp://region/us-west-1myapp://region/ap-northeast-2myapp://region/eu-west-3
But it doesn't match with:
myapp://region/ca-central-1
For additional information, see the implementation of default URL Value Converters.
URLNavigator is under MIT license. See the LICENSE file for more info.