Latest1.0.1
Homepagehttps://github.com/Zuikyo/ZIKRouter
LicenseMIT
Platformsios 7.0, requires ARC
FrameworksFoundation, UIKit
Authors

ZIKRouter

ZIKRouter
ZIKRouter
ZIKRouter
ZIKRouter
ZRouter
license

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

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

The service router can discover and prepare corresponding module with it’s protocol.


一个用于模块间路由,基于接口进行模块发现和依赖注入的解耦工具。

View router 将 UIKit 中的所有界面跳转方式封装成一个统一的方法。

Service router 用于模块寻找,通过 protocol 寻找对应的模块,并用 protocol 进行依赖注入和模块调用。可和其他 URL router 兼容。

中文文档


Features

  • [x] Support Swift and Objective-C
  • [x] Routing for UIViewController, UIView and any classes
  • [x] Dependency injection
  • [x] Locate module with it’s protocol
  • [x] Locate module with identifier, compatible with other URL router
  • [x] Prepare the module with it’s protocol when performing route, rather than passing a parameter dictionary
  • [x] Use different adapter protocols inside module and module’s user for the same module to make thorough decouple
  • [x] Declare routable protocol. There’re compile-time checking and runtime checking to make routing reliable
  • [x] Declare a specific router with generic parameters
  • [x] Decouple modules and add compatible interfaces with adapter
  • [x] Encapsulate navigation methods in UIKit (push, present modally, present as popover, segue, show, showDetail, addChildViewController, addSubview) and custom transitions into one method
  • [x] Remove a UIviewController/UIView or unload a module through one method, without using pop、dismiss、removeFromParentViewController、removeFromSuperview in different situation. Router can choose the proper method
  • [x] Support storyboard. UIViewController and UIView from a segue can auto create it’s registered router
  • [x] Error checking for UIKit view transition
  • [x] AOP for view transition
  • [x] Auto register all routers, or manually register each router
  • [x] Add route with router subclasses, or with blocks
  • [ ] Support Mac OS and tv OS (only iOS now)

Table of Contents

Basics

  1. Router Implementation
  2. Module Registration
  3. Routable Declaration
  4. Type Checking
  5. Perform Route
  6. Remove Route
  7. Make Destination

Advanced Features

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

Requirements

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

Installation

Cocoapods

For Objective-C project:

pod 'ZIKRouter', '>= 1.0.1'

For Swift project:

pod 'ZRouter', '>= 1.0.1'

Sample

View Router

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
“`

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)
}

Transition and Prepare

Transition to editor view, and prepare it before transition:

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
                config.successHandler = { destination in
                    //Transition succeed
                }
                config.errorHandler = { (action, error) in
                    //Transition failed
                }
                //Prepare the destination before transition
                config.prepareDestination = { [weak self] destination in
                    //destination is inferred as NoteEditorInput
                    destination.delegate = self
                    destination.constructForCreatingNewNote()
                }
        })
    }
}
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 = ^(SEL routeAction, NSError * error) {
//Transition failed
};
}];
}

@end
“`

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))
    }

    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)];
}

– (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
“`

Service Router

Get a module and use:

///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.

How to use

Quick start to use ZIKRouter.

1.Create Router

Create router subclass for your module:

import ZIKRouter.Internal
import ZRouter

class NoteEditorViewRouter: ZIKViewRouter<NoteEditorViewController, ViewRouteConfig> {
    override class func registerRoutableDestination() {
        registerView(NoteEditorViewController.self)
        register(RoutableView<NoteEditorInput>())
    }

    override func destination(with configuration: ViewRouteConfig) -> NoteEditorViewController? {
        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 {
[self registerView:[NoteEditorViewController class]];
[self registerViewProtocol:ZIKRoutable(NoteEditorInput)];
}

– (NoteEditorViewController *)destinationWithConfiguration:(ZIKViewRouteConfiguration *)configuration {
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.

2.Declare Routable Type

//Declare NoteEditorViewController is routable
extension NoteEditorViewController: ZIKRoutableView {
}

//Declare NoteEditorInput is routable
extension RoutableView where Protocol == NoteEditorInput {
    init() { self.init(declaredProtocol: Protocol.self) }
}
Objective-C Sample

“`objectivec
//Declare NoteEditorViewController is routable
DeclareRoutableView(NoteEditorViewController, NoteEditorViewRouter)

///If the protocol inherits from ZIKViewRoutable, it’s routable
@protocol NoteEditorInput
@property (nonatomic, weak) id delegate;
– (void)constructForCreatingNewNote;
@end
“`

3.Use

class TestViewController: UIViewController {

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

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

“`objectivec
@implementation TestViewController

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

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

@end
“`

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": "ZIKRouter",
    "version": "1.0.1",
    "summary": "Interface-Oriented iOS router for discovering modules and injecting dependencies with protocol in both Swift and Objective-C.",
    "description": "Interface-Oriented iOS router for discovering modules and injecting dependencies with protocol in both Swift and Objective-C, 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": "7.0"
    },
    "source": {
        "git": "https://github.com/Zuikyo/ZIKRouter.git",
        "tag": "1.0.1"
    },
    "frameworks": [
        "Foundation",
        "UIKit"
    ],
    "requires_arc": true,
    "preserve_paths": "ZIKRouter/Framework/module.modulemap",
    "module_map": "ZIKRouter/Framework/module.modulemap",
    "source_files": [
        "ZIKRouter/Router/*.{h,m,mm,cpp}",
        "ZIKRouter/Router/**/*.{h,m,mm,cpp}",
        "ZIKRouter/ServiceRouter/*.{h,m,mm,cpp}",
        "ZIKRouter/ServiceRouter/**/*.{h,m,mm,cpp}",
        "ZIKRouter/ViewRouter/*.{h,m,mm,cpp}",
        "ZIKRouter/ViewRouter/**/*.{h,m,mm,cpp}",
        "ZIKRouter/ViewRouter/**/**/*.{h,m,mm,cpp}",
        "ZIKRouter/Utilities/*.{h,m,mm,cpp}",
        "ZIKRouter/Utilities/**/*.{h,m,mm,cpp}",
        "ZIKRouter/Utilities/**/**/*.{h,m,mm,cpp}",
        "ZIKRouter/Framework/*.h"
    ],
    "public_header_files": [
        "ZIKRouter/*.h",
        "ZIKRouter/Router/*.h",
        "ZIKRouter/Router/**/*.h",
        "ZIKRouter/ServiceRouter/*.h",
        "ZIKRouter/ServiceRouter/**/*.h",
        "ZIKRouter/ViewRouter/*.h",
        "ZIKRouter/ViewRouter/**/*.h",
        "ZIKRouter/Utilities/*.h",
        "ZIKRouter/Framework/*.h"
    ],
    "private_header_files": [
        "ZIKRouter/Router/Private/*.h",
        "ZIKRouter/ServiceRouter/BlockRouter/ZIKBlockServiceRouter.h",
        "ZIKRouter/ViewRouter/Private/*.h",
        "ZIKRouter/ViewRouter/BlockRouter/BlockViewRouters/*.h"
    ]
}

Pin It on Pinterest

Share This