Routable是iOS中的原生URL路由器,也是Android的支持者。
设置您的应用路由器和URLs(通常在application:didFinishLaunchingWithOptions:
中完成)
[[Routable sharedRouter] map:@"users/:id" toController:[UserController class]];
// Requires an instance of UINavigationController to open UIViewControllers
[[Routable sharedRouter] setNavigationController:aNavigationController];
在您的UIViewController
子类中实现initWithRouterParams:
@implementation UserController
// params will be non-nil
- (id)initWithRouterParams:(NSDictionary *)params {
if ((self = [self initWithNibName:nil bundle:nil])) {
self.userId = [params objectForKey:@"id"];
}
return self;
}
然后,在您应用中的任何地方,打开一个URL
NSString *aUrl = @"users/4";
[[Routable sharedRouter] open:aUrl];
如果您想自定义控制器的分配,可以使用+allocWithRouterParams:
[[Routable sharedRouter] map:@"users/:id" toController:[StoryboardController class]];
@implementation StoryboardController
+ (id)allocWithRouterParams:(NSDictionary *)params {
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Storyboard" bundle:nil];
StoryboardController *instance = [storyboard instantiateViewControllerWithIdentifier:@"sbController"];
instance.userId = [params objectForKey:@"id"];
return instance;
}
设置ignoresExceptions
为YES
以不抛出异常(建议用于发布/分发版本)
[[Routable sharedRouter] setIgnoresExceptions:YES];
您可以使用Routable调用匿名回调
[[Routable sharedRouter] map:@"invalidate/:id" toCallback:^(NSDictionary *params) {
[Cache invalidate: [params objectForKey:@"id"]]];
}];
[[Routable sharedRouter] open:@"invalidate/5h1b2bs"];
您可以使用UPRouterOptions
配置是否以及如何模态方式展示UIViewController
UPRouterOptions *options = [[UPRouterOptions modal] withPresentationStyle: UIModalPresentationFormSheet];
[self.router map:@"info" toController:[InfoController class]
withOptions:options];
UPRouterOptions
有以下DSL设置器
modal
withPresentationStyle
withTransitionStyle
forDefaultParams
有时您想要在您的应用之外打开一个URL,比如一个YouTube URL或者在浏览器中打开一个网页URL。您可以使用Routable来实现这个功能
[[Routable sharedRouter] openExternal:@"http://www.youtube.com/watch?v=oHg5SJYRHA0"];
如果您需要使用多个路由器,简单地创建新的Router
实例
UPRouter *adminRouter = [Routable newRouter];
[adminRouter map:@"profile" toController: [AdminProfile class]];
UPRouter *userRouter = [Routable newRouter];
[userRouter map:@"profile" toController: [UserProfile class]];
Clay Allsopp (http://clayallsopp.com)
适用于iOS的Routable采用MIT许可证。有关更多信息,请参阅LICENSE文件。