WZBridge
示例
一个简单的 JavaScript 和本地交互桥梁 WKWebView
灵感来源于 EasyJSWebView 和 dsBridge
要运行示例项目,请克隆仓库,然后首先在 Example 目录下运行 pod install
用法
- 在一个类中实现 API
@protocol WZObjCApiTestExport <WZJSExport>
@required
- (void)callSyn;
- (NSString *)callSyn:(NSString *)msg;
- (void)callAsyn:(NSString *)msg :(WJSCallFunction *)func;
- (void)callAsyn:(WJSCallFunction *)func;
@optional
- (void)callProgress:(WJSCallFunction *)func;
@end
@interface WZObjCApiTest : NSObject<WZObjCApiTestExport>
@end
@implementation WZObjCApiTest
{
NSTimer *_timer;
int _t;
WJSCallFunction *_func;
}
#pragma mark - to implement protocol method
- (void)callAsyn:(nonnull WJSCallFunction *)func {
NSLog(@"%s Hello, I am js",__func__);
[func executeWithParam:@"hellow js ,I am ObjC ,I received your message" completionHandler:^(NSString * _Nullable result, NSError * _Nullable error) {
NSLog(@"%@",result);
}];
}
- (void)callAsyn:(nonnull NSString *)msg :(nonnull WJSCallFunction *)func {
NSLog(@"%s Hello, I am js",__func__);
[func executeWithParam:[NSString stringWithFormat:@"hellow js ,I am ObjC ,I received your message:%@",msg] completionHandler:^(NSString * _Nullable result, NSError * _Nullable error) {
NSLog(@"%@",result);
}];
}
- (void)callSyn {
NSLog(@"%s Hello, I am js",__func__);
}
- (nonnull NSString *)callSyn:(nonnull NSString *)msg {
NSLog(@"%s Hello, I am js",__func__);
return [NSString stringWithFormat:@"hellow js ,I am ObjC ,I received your message:%@",msg];
}
- (void)callProgress:(WJSCallFunction *)func
{
if (_func) {
[_timer invalidate];
_timer = nil;
_func.removeAfterExecute = YES;
[_func executeWithParam:@""];
}
_func = func;
_func.removeAfterExecute = NO;
_t = 10;
[_func executeWithParam:@(_t).stringValue completionHandler:nil];
_timer = [NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:@selector(onTimer:)
userInfo:nil
repeats:YES];
}
- (void)onTimer:(NSTimer *)timer
{
_t--;
if (_t > 0) {
[_func executeWithParam:@(_t).stringValue];
}else{
_func.removeAfterExecute = YES;
[_func executeWithParam:@(0).stringValue];
[_timer invalidate];
_timer = nil;
}
}
@end
- 将 API 对象添加到 WWKWebView
WWKWebView *webView = [WWKWebView new];
[webView addJavascriptObject:[WZObjCApiTest new] namespace:@"toObjC"];
/// custom dialogText
[webView setDialogText:@"启禀陛下:" forKey:WWKWebViewDialogKeyAlertTitle];
/// monitor title or progress
[webView addObserverForType:WWObserverTypeProgress block:^(id _Nonnull value) {
NSLog(@"block progress is :%@",value);
}];
[webView addObserverForType:WWObserverTypeTitle target:self selector:@selector(setTitle:)];
- 在 Javascript 中调用本地 (ObjC/Swift) API
toObjC.callSyn()
var fromObjC = toObjC.callSyn("Hellow! I'm js!")
toObjC.callAsyn("Hellow! I'm js!",function(v){
return "OK ,I received your message:" + v;
})
toObjC.callAsyn(function(v){
return "OK ,I received your message:" + v;
})
安装
WZBridge 通过 CocoaPods 提供。要安装它,只需将以下行添加到 podfile 中
pod 'WZBridge'
作者
弧光天使w, [email protected]
许可证
WZBridge 采用MIT许可证。更多信息请参阅LICENSE文件。