有更好的方式来处理整个应用数据传输。我们遇到了许多应用程序缺乏美丽的代码,模块依赖真的很遗憾。
想想看,如果你想知道呼叫一个类方法,你必须导入类,然后创建或使用类的单例,然后调用它的成员或方法。你甚至不知道,如果类改变了。一旦你导入了类,你也导入了类的依赖。这不好!
PonyRouter 尝试解决这个问题。
让我们猜猜,如果类 > 类调用改为类 > URL > 类调用,它会更简单吗?
常见风格
//File ClassA.m
@implementation ClassA
- (NSString *)sayHello {
return @"Hello";
}
@end
//File ClassB.m
#import "ClassA.h"
@implementation ClassB
- (void)main {
ClassA *a = [[ClassA alloc] init];
NSLog(@"%@", a.sayHello);
}
@end
PonyRouter 风格
//File ClassA.m
@implementation ClassA
+ (void)load {
PGRNode *node = [[PGRNode alloc] initWithIdentifier:@"wechat://sayhello/" returnableBlock:^id(NSURL *sourceURL, NSDictionary *params, NSObject *sourceObject) {
ClassA *a = [[ClassA alloc] init];
return a.sayHello;
}];
[[PGRApplication sharedInstance] addNode:node];
}
- (NSString *)sayHello {
return @"Hello";
}
@end
//File ClassB.m
//No need to import ClassA.h now!
- (void)main {
NSLog(@"%@", [[PGRApplication sharedInstance] openURL:[NSURL URLWithString:@"wechat://sayhello/"]]);
}
PGR 接受路径信息样式 URL(例如 wechat://sayhello/key1/value1/key2/value2....),PGR 还接受查询字符串样式 URL(例如 wechat://sayhello/?key1=value1&key2=value2...)。
例如
NSURL *URL = [NSURL URLWithString:@"demoApp://sayhello/?k1=v1&k2=v2"];
[[UIApplication sharedApplication] openURL:URL];
[node setExecutingBlock:^(NSURL *sourceURL, NSDictionary *params, NSObject *sourceObject) {
NSLog(@"%@",params);
}];
/*
Conlose loged:
2015-10-30 11:19:52.216 PonyRouter[76507:948438] {
k1 = v1;
k2 = v2;
}
*/
PGR 接受模式 URL。
PGRNode *node = [[PGRNode alloc] initWithIdentifier:@".*?" scheme:@"test" usePattern:YES executingBlock:^(NSURL *sourceURL, NSDictionary *params, NSObject *sourceObject) {
}];
以下定义如下,包含 test://.*?
的 URL 将被接受。
您可以同步返回对象,并按您的要求使用它。
PGRNode *node = [[PGRNode alloc] initWithIdentifier:@"kissme" returnableBlock:^id(NSURL *sourceURL, NSDictionary *params, NSObject *sourceObject) {
return [NSString stringWithFormat:@"%@ kissed me.", params[@"someone"]];
}];
NSURL *URL = [NSURL URLWithString:@"demoApp://kissme/?someone=Pony"];
NSString *whoKissMe = [[PGRApplication sharedInstance] openURL:URL];
[[[UIAlertView alloc] initWithTitle:nil message:whoKissMe delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil] show];
PonyRouter 向 URL 协议添加了一个钩子,因此您可以发送通过 NSURLConnect 或 webView AJAX jQuery 请求,返回值将作为响应数据接收。
这是从 webView 传递消息到应用程序的简单方法。
不用担心主线程阻塞,它将像 GCD 异步线程一样调用。