UIWebView –app 调用 js
web页面和app直接的交互是很常见的东西。ios的WebView有两个类,一个叫UIWebView,另一个是WKWebView。
ios9默认是不允许加载http请求的,对于web view,加载http网页也是不允许的。
可以通过修改info.plist取消http限制
在项目中找到info.plist,以source code方式打开,添加下面的内容
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
从IOS7开始,苹果公布了JavaScriptCore.framework ,它似的JS与OC的交互更加方便了。下面就简单了解下这个框架。
1. 首先导入framework,方法如下:
2.点击”Linked Frameworks and Libraries”,选择“JavaScriptCore.framework”
3.在viewController中导入头文件
#import <JavaScriptCore/JavaScriptCore.h>
4.在ViewController中创建一个UIWebView用来测试
@interface ViewController()<UIWebViewDelegate>
@property(nonatomic,strong)UIWebView *myWebView;
@end
@implementation ViewController
-(void)viewDidLoad{
self.myWebView = [UIWebView alloc] initWithFrame:CGRectMake(0,22,[UIScreen mainScreen].bounds.size.width,[UIScreen mainScreen].bounds.size.height-22)];
self.myWebView.delegate = self;
[self.view addSubView:self.myWebView];
//网址
NSString *httpStr = @"http://www.baidu.com";
NSURL *url = [NSURL URLWithString:httpStr];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.myWebView loadRequest:request];
}
5.添加协议
@interface ViewController()<UIWebViewDelegate>
实现UIWebViewDelegate代理方法
#pragma mark --webViewDelegate
-(void)webViewDidFinishLoad:(UIWebView*)webView{
//网页加载完成调用此方法
//首先创建JSContext对象(此处通过webView的键获取到jscontext)
JSContext *context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
//准备执行的js代码
NSString *alertStr = @"alert('vic test invoke js')";
//通过oc方法调用js的alert
[context evaluateScript:alertStr];
}
运行效果如下: