OC原生代码/webview与js/网页交互的最好方式

来源:互联网 发布:河北js防水厂家 编辑:程序博客网 时间:2024/05/17 03:08
利用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>
@protocolPublicProtocol<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];
}
0 0