Latest 1.0.9
Homepage https://github.com/Zuikyo/ZIKRouter
License MIT
Platforms ios 8.0, osx 10.10, tvos 9.0, requires ARC
Authors

ZRouter

ZIKRouter

ZRouter
ZRouter
ZRouter
ZIKRouter
Carthage compatible
license

An interface-oriented router for discovering modules and injecting dependencies with protocol.

The view router can perform all navigation types in UIKit / AppKit through one method.

The service router can discover and prepare corresponding module with its protocol.


一个用于模块间解耦和通信,基于接口进行模块管理和依赖注入的组件化路由工具。

通过 protocol 寻找对应的模块,并用 protocol 进行依赖注入和模块通信。

View router 将 UIKit / AppKit 中的所有界面跳转方式封装成一个统一的方法。Service router 用于支持任意自定义模块。

中文文档


Features

  • [x] Support Swift and Objective-C
  • [x] Support iOS, macOS and tvOS
  • [x] Routing for UIViewController / NSViewController, UIView / NSView and any OC class and swift class
  • [x] Dependency injection, including dynamic injection and static injection
  • [x] Declare routable protocol for compile-time checking. Using undeclared protocol will bring compile error. This is one of the most powerful feature
  • [x] Locate module with its protocol
  • [x] Locate module with identifier, compatible with other URL router frameworks
  • [x] Prepare the module with its protocol when performing route, rather than passing a parameter dictionary
  • [x] Use different required protocol and provided protocol inside module and module’s user to make thorough decouple
  • [x] Decouple modules and add compatible interfaces with adapter
  • [x] Support storyboard. UIViewController / NSViewController and UIView / NSView from a segue can auto create it’s registered router
  • [x] Encapsulate navigation methods in UIKit and AppKit (push, present modally, present as popover present as sheet, segue, show, showDetail, addChildViewController, addSubview) and custom transitions into one method
  • [x] Remove an UIViewController/UIView or unload a module through one method, without using pop、dismiss、removeFromParentViewController、removeFromSuperview in different situations. Router can choose the proper method
  • [x] Error checking for view transition
  • [x] AOP for view transition
  • [x] Detect memory leaks
  • [x] Send custom events to router
  • [x] Auto register all routers

Documentation

Design Idea

Design Idea

Basics

  1. Router Implementation
  2. Module Registration
  3. Routable Declaration
  4. Type Checking
  5. Perform Route
  6. Remove Route
  7. Transfer Parameters with Custom Configuration

Advanced Features

  1. Error Handle
  2. Storyboard and Auto Create
  3. AOP
  4. Dependency Injection
  5. Circular Dependency
  6. Module Adapter

FAQ

Quick Start Guide

  1. Create Router
    1. Router Subclass
    2. Simple Router
  2. Declare Routable Type
  3. View Router
    1. Transition directly
    2. Prepare before Transition
    3. Make Destination
    4. Transfer Parameters in a Powerful Pattern
    5. Remove
    6. Adapter
    7. URL Router
  4. Service Router
  5. Demo and Practice
  6. File Template

Requirements

  • iOS 7.0+
  • Swift 3.2+
  • Xcode 9.0+

Installation

Cocoapods

Add this to your Podfile.

For Objective-C project:

pod 'ZIKRouter', '>= 1.0.9'

# or only use ServiceRouter
pod 'ZIKRouter/ServiceRouter' , '>=1.0.9'

For Swift project:

pod 'ZRouter', '>= 1.0.9'

# or only use ServiceRouter
pod 'ZRouter/ServiceRouter' , '>=1.0.9'

Carthage

Add this to your Cartfile:

github "Zuikyo/ZIKRouter" >= 1.0.9

Build frameworks:

carthage update

Build DEBUG version to enable route checking:

carthage update --configuration Debug

Remember to use release version in production environment.

For Objective-C project, use ZIKRouter.framework. For Swift project, use ZRouter.framework.

Getting Started

This is the demo view controller and protocol:

///Editor view's interface
protocol NoteEditorInput: class {
    weak var delegate: EditorDelegate? { get set }
    func constructForCreatingNewNote()
}

///Editor view controller
class NoteEditorViewController: UIViewController, NoteEditorInput {
    ...
}
Objective-C Sample

“`objectivec
///editor view’s interface
@protocol NoteEditorInput
@property (nonatomic, weak) id delegate;
– (void)constructForCreatingNewNote;
@end
“`

“`objectivec
///Editor view controller
@interface NoteEditorViewController: UIViewController
@end
@implementation NoteEditorViewController
@end
“`

There’re 2 steps to create route for your module.

1. Create Router

To make your class become modular, you need to create router for your module. You don’t need to modify the module’s code. That will reduce the cost for refactoring existing modules.

1.1 Router Subclass

Create router subclass for your module:

import ZIKRouter.Internal
import ZRouter

class NoteEditorViewRouter: ZIKViewRouter<NoteEditorViewController, ViewRouteConfig> {
    override class func registerRoutableDestination() {
        // Register class with this router. A router can register multi views, and a view can be registered with multi routers
        registerView(NoteEditorViewController.self)
        // Register protocol. Then we can fetch this router with the protocol
        register(RoutableView<NoteEditorInput>())
    }

    // Return the destination module
    override func destination(with configuration: ViewRouteConfig) -> NoteEditorViewController? {
        // In configuration, you can get parameters from the caller for creating the instance
        let destination: NoteEditorViewController? = ... /// instantiate your view controller
        return destination
    }

    override func prepareDestination(_ destination: NoteEditorViewController, configuration: ViewRouteConfig) {
        // Inject dependencies to destination
    }
}
Objective-C Sample

“`objectivec
//NoteEditorViewRouter.h
@import ZIKRouter;

@interface NoteEditorViewRouter : ZIKViewRouter
@end

//NoteEditorViewRouter.m
@import ZIKRouter.Internal;

@implementation NoteEditorViewRouter

+ (void)registerRoutableDestination {
// Register class with this router. A router can register multi views, and a view can be registered with multi routers
[self registerView:[NoteEditorViewController class]];
// Register protocol. Then we can fetch this router with the protocol
[self registerViewProtocol:ZIKRoutable(NoteEditorInput)];
}

// Return the destination module
– (NoteEditorViewController *)destinationWithConfiguration:(ZIKViewRouteConfiguration *)configuration {
// In configuration, you can get parameters from the caller for creating the instance
NoteEditorViewController *destination = … // instantiate your view controller
return destination;
}

– (void)prepareDestination:(NoteEditorViewController *)destination configuration:(ZIKViewRouteConfiguration *)configuration {
// Inject dependencies to destination
}

@end
“`

Read the documentation for more details and more methods to override.

1.2 Simple Router

If your module is very simple and don’t need a router subclass, you can just register the class in a simpler way:

ZIKAnyViewRouter.register(RoutableView<NoteEditorInput>(), forMakingView: NoteEditorViewController.self)
Objective-C Sample

“`objectivec
[ZIKViewRouter registerViewProtocol:ZIKRoutable(NoteEditorInput) forMakingView:[NoteEditorViewController class]];
“`

or with custom creating block:

ZIKAnyViewRouter.register(RoutableView<NoteEditorInput>(), 
                 forMakingView: NoteEditorViewController.self) { (config, router) -> NoteEditorInput? in
                     NoteEditorViewController *destination = ... // instantiate your view controller
                     return destination;
        }
Objective-C Sample

“`objectivec
[ZIKViewRouter
registerViewProtocol:ZIKRoutable(NoteEditorInput)
forMakingView:[NoteEditorViewController class]
making:^id _Nullable(ZIKViewRouteConfiguration *config, ZIKViewRouter *router) {
NoteEditorViewController *destination = … // instantiate your view controller
return destination;
}];
“`

or with custom factory function:

function makeEditorViewController(config: ViewRouteConfig) -> NoteEditorInput? {
    NoteEditorViewController *destination = ... // instantiate your view controller
    return destination;
}

ZIKAnyViewRouter.register(RoutableView<NoteEditorInput>(), 
                 forMakingView: NoteEditorViewController.self, making: makeEditorViewController)
Objective-C Sample

“`objectivec
id makeEditorViewController(ZIKViewRouteConfiguration *config) {
NoteEditorViewController *destination = … // instantiate your view controller
return destination;
}

[ZIKViewRouter
registerViewProtocol:ZIKRoutable(NoteEditorInput)
forMakingView:[NoteEditorViewController class]
factory:makeEditorViewController];
“`

2. Declare Routable Type

The declaration is for checking routes at compile time, and supporting storyboard.

// Declare NoteEditorViewController is routable
// This means there is a router for NoteEditorViewController
extension NoteEditorViewController: ZIKRoutableView {
}

// Declare NoteEditorInput is routable
// This means you can use NoteEditorInput to fetch router
extension RoutableView where Protocol == NoteEditorInput {
    init() { self.init(declaredProtocol: Protocol.self) }
}
Objective-C Sample

“`objectivec
// Declare NoteEditorViewController is routable
// This means there is a router for NoteEditorViewController
DeclareRoutableView(NoteEditorViewController, NoteEditorViewRouter)

// If the protocol inherits from ZIKViewRoutable, it’s routable
// This means you can use NoteEditorInput to fetch router
// If you use an undeclared protocol, there will be compile time warning
@protocol NoteEditorInput
@property (nonatomic, weak) id delegate;
– (void)constructForCreatingNewNote;
@end
“`

If you use an undeclared protocol for routing, there will be compile time error.

Now you can get and show NoteEditorViewController with router.

View Router

Transition directly

Transition to editor view directly:

class TestViewController: UIViewController {

    // Transition to editor view directly
    func showEditorDirectly() {
        Router.perform(to: RoutableView<NoteEditorInput>(), path: .push(from: self))
    }
}
Objective-C Sample

“`objectivec
@implementation TestViewController

– (void)showEditorDirectly {
// Transition to editor view directly
[ZIKRouterToView(NoteEditorInput) performPath:ZIKViewRoutePath.pushFrom(self)];
}

@end
“`

You can change transition type with ViewRoutePath:

enum ViewRoutePath {
    case push(from: UIViewController)
    case presentModally(from: UIViewController)
    case presentAsPopover(from: UIViewController, configure: ZIKViewRoutePopoverConfigure)
    case performSegue(from: UIViewController, identifier: String, sender: Any?)
    case show(from: UIViewController)
    case showDetail(from: UIViewController)
    case addAsChildViewController(from: UIViewController, addingChildViewHandler: (UIViewController, @escaping () -> Void) -> Void)
    case addAsSubview(from: UIView)
    case custom(from: ZIKViewRouteSource?)
    case makeDestination
    case extensible(path: ZIKViewRoutePath)
}

Prepare before Transition

Prepare it before transition to editor view:

class TestViewController: UIViewController {

    // Transition to editor view, and prepare the destination with NoteEditorInput
    func showEditor() {
        Router.perform(
            to: RoutableView<NoteEditorInput>(),
            path: .push(from: self),
            configuring: { (config, _) in
                // Route config
                // Prepare the destination before transition
                config.prepareDestination = { [weak self] destination in
                    //destination is inferred as NoteEditorInput
                    destination.delegate = self
                    destination.constructForCreatingNewNote()
                }
                config.successHandler = { destination in
                    // Transition succeed
                }
                config.errorHandler = { (action, error) in
                    // Transition failed
                }                
        })
    }
}
Objective-C Sample

“`objectivec
@implementation TestViewController

– (void)showEditor {
// Transition to editor view, and prepare the destination with NoteEditorInput
[ZIKRouterToView(NoteEditorInput)
performPath:ZIKViewRoutePath.pushFrom(self)
configuring:^(ZIKViewRouteConfig *config) {
// Route config
// Prepare the destination before transition
config.prepareDestination = ^(id destination) {
destination.delegate = self;
[destination constructForCreatingNewNote];
};
config.successHandler = ^(id destination) {
// Transition is completed
};
config.errorHandler = ^(ZIKRouteAction routeAction, NSError * error) {
// Transition failed
};
}];
}

@end
“`

For more detail, read Perform Route.

Make Destination

If you don’t wan’t to show a view, but only need to get instance of the module, you can use makeDestination:

// destination is inferred as NoteEditorInput
let destination = Router.makeDestination(to: RoutableView<NoteEditorInput>())
Objective-C Sample

“`objectivec
id destination = [ZIKRouterToView(NoteEditorInput) makeDestination];
“`

Transfer Parameters in a Powerful Pattern

Sometimes the destination class uses custom initializers to create instance, router needs to get required parameter from the caller.

Sometimes your module contains multi components, and you need to pass parameters to those components. And those parameters do not belong to the destination.

You can use module config protocol and a custom configuration to transfer parameters.

Instead of NoteEditorInput, we use another routable protocol EditorViewModuleInput as config protocol for routing:

// In general, a module config protocol only contains `constructDestination`and`didMakeDestination`, for declaring parameters and destination type. You can also add other properties or methods
protocol EditorViewModuleInput: class {
    // Transfer parameters for making destination
    var constructDestination: (_ note: Note) -> Void { get }
    // Declare that destination type is NoteEditorInput
    var didMakeDestination: ((NoteEditorInput) -> Void)? { get set }
}
Objective-C Sample

“`objectivec
// In general, a module config protocol only contains `constructDestination`and`didMakeDestination`, for declaring parameters and destination type. You can also add other properties or methods
@protocol EditorViewModuleInput
// Transfer parameters for making destination
@property (nonatomic, copy, readonly) void(^constructDestination)(Note *note);
// Declare that destination type is NoteEditorInput
@property (nonatomic, copy, nullable) void(^didMakeDestination)(id destination);
@end
“`

You can use a configuration subclass and store parameters on its properties.

configuration subclass

“`swift
// Configuration subclass conforming to EditorViewModuleInput
// Swift generic class is not OC Class. It won’t be in the `__objc_classlist` section of the Mach-O file. So it won’t affect the app launching time.
class EditorViewModuleConfiguration: ZIKViewMakeableConfiguration, EditorViewModuleInput {
var didMakeDestination: ((NoteEditorInput) -> Void)?

// User is responsible for calling constructDestination and giving parameters
var constructDestination: (_ note: Note) -> Void {
return { note in
// Capture parameters in makeDestination, so we don’t need configuration subclass to hold the parameters
// MakeDestination will be used for creating destination instance
self.makeDestination = { [unowned self] () in
// Use custom initializer
let destination = NoteEditorViewController(note: note)
// Give destination to the caller
self.didMakeDestination?(destination)
self.didMakeDestination = nil
return destination
}
}
}
}

func makeEditorViewModuleConfiguration() -> ZIKViewMakeableConfiguration & EditorViewModuleInput {
return EditorViewModuleConfiguration()
}
“`

If the protocol is very simple and you don’t need a configuration subclass,or you’re using Objective-C and don’t want too many subclass, you can choose generic classViewMakeableConfigurationandZIKViewMakeableConfiguration:

extension ViewMakeableConfiguration: EditorViewModuleInput where Destination == NoteEditorInput, Constructor == (Note) -> Void {
}

// ViewMakeableConfiguration with generic arguments works as the same as  EditorViewModuleConfiguration
// The config works like EditorViewModuleConfiguration<Any>()
func makeEditorViewModuleConfiguration() -> ViewMakeableConfiguration<NoteEditorInput, (Note) -> Void> {
    let config = ViewMakeableConfiguration<NoteEditorInput, (Note) -> Void>({ _,_ in})

    // User is responsible for calling constructDestination and giving parameters
    config.constructDestination = { [unowned config] note in
        // Capture parameters in makeDestination, so we don't need configuration subclass to hold the parameters
        // MakeDestination will be used for creating destination instance
        config.makeDestination = { () in
            // Use custom initializer
            let destination = NoteEditorViewController(note: note)
            return destination
        }
    }
    return config
}
Objective-C Sample

Generic class`ZIKViewMakeableConfiguration`has property`constructDestination`with`void(^)()`type. `void(^)()`means the block can accept any parameters. So you can declare your custom parameters of `constructDestination` in protocol.

“`objectivec
// The config works like EditorViewModuleConfiguration
ZIKViewMakeableConfiguration * makeEditorViewModuleConfiguration() {
ZIKViewMakeableConfiguration *config = [ZIKViewMakeableConfiguration new];
__weak typeof(config) weakConfig = config;

// User is responsible for calling constructDestination and giving parameters
config.constructDestination = ^(Note *note) {
// Capture parameters in makeDestination, so we don’t need configuration subclass to hold the parameters
// MakeDestination will be used for creating destination instance
weakConfig.makeDestination = ^ NoteEditorViewController * _Nullable{
// Use custom initializer
NoteEditorViewController *destination = [NoteEditorViewController alloc] initWithNote:note];
return destination;
};
};
return config;
}
“`

OverridedefaultRouteConfigurationin router to use your custom configuration:

class EditorViewRouter: ZIKViewRouter<NoteEditorViewController, ZIKViewMakeableConfiguration<NoteEditorViewController>> {

    override class func registerRoutableDestination() {
        // Register class
        registerView(NoteEditorViewController.self)
        // Register module config protocol, then we can use this protocol to fetch the router
        register(RoutableViewModule<EditorViewModuleInput>())
    }

    // Use custom configuration
    override class func defaultRouteConfiguration() -> ZIKViewMakeableConfiguration<NoteEditorViewController> {
        return makeEditorViewModuleConfiguration()
    }

    override func destination(with configuration: ZIKViewMakeableConfiguration<NoteEditorViewController>) -> NoteEditorViewController? {
        if let makeDestination = configuration.makeDestination {
            return makeDestination()
        }
        return nil
    }
    ...
}
Objective-C Sample

“`swift
@interface EditorViewRouter: ZIKViewRouter>
@end
@implementation EditorViewRouter {

+ (void) registerRoutableDestination {
// Register class
[self registerView:[NoteEditorViewController class]];
// Register module config protocol, then we can use this protocol to fetch the router
[self registerModuleProtocol:ZIKRoutable(EditorViewModuleInput)];
}

// Use custom configuration
+(ZIKViewMakeableConfiguration *)defaultRouteConfiguration() {
return makeEditorViewModuleConfiguration();
}

– (NoteEditorViewController *)destinationWithConfiguration:(ZIKViewMakeableConfiguration *)configuration {
if (configuration.makeDestination) {
return configuration.makeDestination();
}
return nil;
}

}
“`

If you’re not using router subclass, you can register config factory to create route:

// Register EditorViewModuleInput and factory function of custom configuration
ZIKAnyViewRouter.register(RoutableViewModule<EditorViewModuleInput>(),
   forMakingView: NoteEditorViewController.self, 
   making: makeEditorViewModuleConfiguration)
Objective-C Sample

“`objectivec
// Register EditorViewModuleInput and factory function of custom configuration
[ZIKModuleViewRouter(EditorViewModuleInput)
registerModuleProtocol:ZIKRoutable(EditorViewModuleInput)
forMakingView:[NoteEditorViewController class]
factory: makeEditorViewModuleConfiguration];
“`

Now the user can use the module with its module config protocol and transfer parameters:

var note = ...
Router.makeDestination(to: RoutableViewModule<EditorViewModuleInput>()) { (config) in
     // Transfer parameters
     config.constructDestination(note)
     config.didMakeDestination = { destiantion in
        // Get NoteEditorInput
     }
}
Objective-C Sample

“`objectivec
Note *note = …
[ZIKRouterToViewModule(EditorViewModuleInput)
performPath:ZIKViewRoutePath.showFrom(self)
configuring:^(ZIKViewRouteConfiguration *config) {
// Transfer parameters
config.constructDestination(note);
config.didMakeDestination = ^(id destination) {
// Get NoteEditorInput
};
}];
“`

In this design pattern, we reduce much glue code for transferring parameters, and the module can re-declare their parameters with generic arguments and module config protocol.

For more detail, read Transfer Parameters with Custom Configuration.

Remove

You can remove the view by removeRoute, without using pop / dismiss / removeFromParentViewController / removeFromSuperview:

class TestViewController: UIViewController {
    var router: DestinationViewRouter<NoteEditorInput>?

    func showEditor() {
        // Hold the router
        router = Router.perform(to: RoutableView<NoteEditorInput>(), path: .push(from: self))
    }

    // Router will pop the editor view controller
    func removeEditorDirectly() {
        guard let router = router, router.canRemove else {
            return
        }
        router.removeRoute()
        router = nil
    }

    func removeEditorWithResult() {
        guard let router = router, router.canRemove else {
            return
        }
        router.removeRoute(successHandler: {
            print("remove success")
        }, errorHandler: { (action, error) in
            print("remove failed, error: (error)")
        })
        router = nil
    }

    func removeEditorAndPrepare() {
        guard let router = router, router.canRemove else {
            return
        }
        router.removeRoute(configuring: { (config) in
                config.animated = true
                config.prepareDestination = { destination in
                    // Use destination before remove it
                }
            })
        router = nil
    }
}
Objective-C Sample

“`objectivec
@interface TestViewController()
@property (nonatomic, strong) ZIKDestinationViewRouter(id) *router;
@end
@implementation TestViewController

– (void)showEditorDirectly {
// Hold the router
self.router = [ZIKRouterToView(NoteEditorInput) performPath:ZIKViewRoutePath.pushFrom(self)];
}

// Router will pop the editor view controller
– (void)removeEditorDirectly {
if (![self.router canRemove]) {
return;
}
[self.router removeRoute];
self.router = nil;
}

– (void)removeEditorWithResult {
if (![self.router canRemove]) {
return;
}
[self.router removeRouteWithSuccessHandler:^{
NSLog(@”pop success”);
} errorHandler:^(ZIKRouteAction routeAction, NSError *error) {
NSLog(@”pop failed,error: %@”,error);
}];
self.router = nil;
}

– (void)removeEditorAndPrepare {
if (![self.router canRemove]) {
return;
}
[self.router removeRouteWithConfiguring:^(ZIKViewRemoveConfiguration *config) {
config.animated = YES;
config.prepareDestination = ^(UIViewController *destination) {
// Use destination before remove it
};
}];
self.router = nil;
}

@end
“`

For more detail, read Remove Route.

Adapter

You can use another protocol to get router, as long as the protocol provides the same interface of the real protocol. Even the protocol is little different from the real protocol, you can adapt two protocols with category, extension and proxy.

Required protocol used by the user:

/// Required protocol to use editor module
protocol RequiredNoteEditorInput: class {
    weak var delegate: EditorDelegate? { get set }
    func constructForCreatingNewNote()
}
Objective-C Sample

“`objectivec
/// Required protocol to use editor module
@protocol RequiredNoteEditorInput
@property (nonatomic, weak) id delegate;
– (void)constructForCreatingNewNote;
@end
“`

UseRequiredNoteEditorInputto get module:

class TestViewController: UIViewController {

    func showEditorDirectly() {
        Router.perform(to: RoutableView<RequiredNoteEditorInput>(), path: .push(from: self))
    }
}
Objective-C Sample

“`objectivec
@implementation TestViewController

– (void)showEditorDirectly {
[ZIKRouterToView(RequiredNoteEditorInput) performPath:ZIKViewRoutePath.pushFrom(self)];
}

@end
“`

Use required protocol and provided protocol to perfectly decouple modules, adapt interface and declare dependencies of the module. And you don’t have to use a public header to manage those protocols.

You need to connect required protocol and provided protocol. For more detail, read Module Adapter.

URL Router

ZIKRouter is also compatible with other URL router frameworks.

You can register string identifier with router:

class NoteEditorViewRouter: ZIKViewRouter<NoteEditorViewController, ViewRouteConfig> {
    override class func registerRoutableDestination() {
        // Register identifier with this router
        registerIdentifier("myapp://noteEditor")
    }
}
Objective-C Sample

“`objectivec
@implementation NoteEditorViewRouter

+ (void)registerRoutableDestination {
// Register identifier with this router
[self registerIdentifier:@”myapp://noteEditor”];
}

@end
“`

Then perform route with the identifier:

Router.to(viewIdentifier: "myapp://noteEditor")?.perform(path .push(from: self))
Objective-C Sample

“`objectivec
[ZIKViewRouter.toIdentifier(@”myapp://noteEditor”) performPath:ZIKViewRoutePath.pushFrom(self)];
“`

And handle URL Scheme:

public func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
        // You can use other URL router frameworks
        let routerIdentifier = URLRouter.routerIdentifierFromURL(url)
        guard let identifier = routerIdentifier else {
            return false
        }
        guard let routerType = Router.to(viewIdentifier: identifier) else {
            return false
        }
        let params: [String : Any] = [ "url": url, "options": options ]
        routerType.perform(path: .show(from: rootViewController), configuring: { (config, _) in
            // Pass parameters
            config.addUserInfo(params)
        })
        return true
    }
Objective-C Sample

“`objectivec
– (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary *)options {

// You can use other URL router frameworks
NSString *identifier = [URLRouter routerIdentifierFromURL:url];
if (identifier == nil) {
return NO;
}
ZIKViewRouterType *routerType = ZIKViewRouter.toIdentifier(identifier);
if (routerType == nil) {
return NO;
}

NSDictionary *params = @{ @”url”: url,
@”options” : options
};
[routerType performPath:ZIKViewRoutePath.showFrom(self.rootViewController)
configuring:^(ZIKViewRouteConfiguration * _Nonnull config) {
// Pass parameters
[config addUserInfo:params];
}];
return YES;
}
“`

Service Router

Instead of view, you can also get any service modules:

/// time service's interface
protocol TimeServiceInput {
    func currentTimeString() -> String
}
class TestViewController: UIViewController {
    @IBOutlet weak var timeLabel: UILabel!

    func callTimeService() {
        // Get the service for TimeServiceInput
        let timeService = Router.makeDestination(
            to: RoutableService<TimeServiceInput>(),
            preparation: { destination in
            // prepare the service if needed
        })
        //Use the service
        timeLabel.text = timeService.currentTimeString()
    }
}
Objective-C Sample

“`objectivec
/// time service’s interface
@protocol TimeServiceInput
– (NSString *)currentTimeString;
@end
“`

“`objectivec
@interface TestViewController ()
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;
@end

@implementation TestViewController

– (void)callTimeService {
// Get the service for TimeServiceInput
id timeService = [ZIKRouterToService(TimeServiceInput) makeDestination];
self.timeLabel.text = [timeService currentTimeString];
}

“`

Demo and Practice

ZIKRouter is designed for VIPER architecture at first. But you can also use it in MVC or anywhere.

The demo (ZIKRouterDemo) in this repository shows how to use ZIKRouter to perform each route type.

If you want to see how it works in a VIPER architecture app, go to ZIKViper.

File Template

You can use Xcode file template to create router and protocol code quickly:

File Template

The template ZIKRouter.xctemplate is in Templates.

Copy ZIKRouter.xctemplate to ~/Library/Developer/Xcode/Templates/ZIKRouter.xctemplate, then you can use it in Xcode -> File -> New -> File -> Templates.

License

ZIKRouter is available under the MIT license. See the LICENSE file for more info.

Latest podspec

{
    "name": "ZRouter",
    "version": "1.0.9",
    "summary": "Interface-Oriented iOS Swift router for discovering modules and injecting dependencies with protocol.",
    "description": "Interface-Oriented iOS Swift router for discovering modules and injecting dependencies with protocol, designed for VIPER. The view router can perform all navigation types in UIKit through one method. The service router can discover service with protocol.",
    "homepage": "https://github.com/Zuikyo/ZIKRouter",
    "license": "MIT",
    "authors": {
        "Zuikyo": "[email protected]"
    },
    "platforms": {
        "ios": "8.0",
        "osx": "10.10",
        "tvos": "9.0"
    },
    "swift_version": "4.0",
    "source": {
        "git": "https://github.com/Zuikyo/ZIKRouter.git",
        "tag": "swift-1.0.9"
    },
    "requires_arc": true,
    "default_subspecs": [
        "ServiceRouter",
        "ViewRouter"
    ],
    "subspecs": [
        {
            "name": "ServiceRouter",
            "dependencies": {
                "ZIKRouter/ServiceRouter": [
                    ">= 1.0.9"
                ]
            },
            "source_files": [
                "ZRouter/*.swift",
                "ZRouter/ServiceRouter/*.swift"
            ]
        },
        {
            "name": "ViewRouter",
            "dependencies": {
                "ZRouter/ServiceRouter": [],
                "ZIKRouter/ViewRouter": [
                    ">= 1.0.9"
                ]
            },
            "source_files": "ZRouter/ViewRouter/*.swift"
        }
    ]
}

Pin It on Pinterest

Share This