利用OC提供的<JavaScriptCore/JavaScriptCore.h>去实现js与oc的交互
第一步继承代理
@interface WebViewViewController ()<
UIWebViewDelegate>
第二步
self.
webCtrl.delegate =
self;
//设置代理
第三步 在实现的协议方法里写上定义js对象的方法
-(
void)webViewDidFinishLoad:(UIWebView *)webView
{
JSContext *context = [self.webCtrl valueForKeyPath:
@"documentView.webView.mainFrame.javaScriptContext"];
//定义好JS要调用的方法
IOSBridge = [[GLBL_APP alloc] init];
context[
@"IOSBridge"] = IOSBridge;
}
第四步 定义和实现js相应的类和实现相应功能代码
#import
<Foundation/Foundation.h>
#import
<JavaScriptCore/JavaScriptCore.h>
@protocol PublicProtocol<JSExport>
//允许网页app访问的对象属性/方法
-(
void)login;
-(
void)shareSong:(NSString*)songId :(NSString*)callback;
@end
@interface GLBL_APP : NSObject<
PublicProtocol>
@property(nonatomic,strong)NSString *callbackName;
@end
#import
"GLBL_APP.h"
@interface GLBL_APP()
{
}
@end
@implementation GLBL_APP
//去登录
-(
void)login{
dispatch_async(dispatch_get_main_queue(), ^{
//始终在主进程中进行
if(![KeychainManager islogin]){
[KeychainManager gotoLogin];
}
});
}
//分享
-(
void)shareSong:(NSString*)songId :(NSString*)callback{
if(![KeychainManager islogin]){
[KeychainManager gotoLogin];
return;
}
//分享
ShareView *shareView = [[ShareView alloc]initWithFrame:CGRectZero];
//赋值歌曲信息
[UserServices
getSongInfoWithSongId:songId userId:[KeychainManager readUserId] completionBlock:^(int result, id responseObject) {
NSDictionary *data=responseObject[@"data"];
shareView.songData = data;
}];
// SongModel *playingMusic = [MusicPlayTools shareMusicPlay].model;
// dfShareView.songData = [playingMusic dictionaryRepresentation];
[shareView showView];
if(callback){
self.callbackName = callback;
}
}
@end
第五步在js中调用
if(IOSBridge){
IOSBridge.shareSong(1207,'test');
}
第六步 在oc里执行JS
NSString *textJS = [NSString stringWithFormat:
@"%@()",actionName];
[context evaluateScript:textJS];
}