打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
iOS 网页 (Webview)代码片段:UIWebView中Html中用JS调用OC方法及OC执行JS代码
HTML代码:
<html>
    <head>
        <title>HTML中用JS调用OC方法</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        [removed]
            function openAlbum()
            {
                // 打开相册(openMyAlbum为OC中的方法)
                [removed].href = 'ios://openMyAlbum';
            }
            function openCamera()
            {
                // 打开相机(openMyCamera为OC中的方法)
                [removed].href = 'ios://openMyCamera';
            }
        [removed]
    </head>
    <body>
        <br/>
        <br/>
        <br/>
        <input type="button" value="打开相机"> <br><br/>
        <input type="button" value="打开相册">
    </body>
</html>
OC代码:
#import "ViewController.h"
@interface ViewController ()<UIWebViewDelegate>
@property (weak, nonatomic) IBOutlet UIWebView *webview;
- (IBAction)getTitle;
@end
@implementation ViewController
- (void)viewDidLoad
{
    [super viewDidLoad];
    NSURL *url = [[NSBundle mainBundle] URLForResource:@"test.html" withExtension:nil];
    [self.webview loadRequest:[NSURLRequest requestWithURL:url]];
    self.webview.delegate = self;
    self.webview.dataDetectorTypes = UIDataDetectorTypeAll;
}
#pragma mark UIWebViewDelegate方法
/**
 *开始加重请求拦截
 */
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSString *urlstr = request.URL.absoluteString;
    NSRange range = [urlstr rangeOfString:@"ios://"];
    if (range.length!=0) {
        NSString *method = [urlstr substringFromIndex:(range.location+range.length)];
        SEL selctor = NSSelectorFromString(method);
        [self performSelector:selctor withObject:nil];
    }
    return YES;
}
/**
 *  OC执行JS代码
 */
- (IBAction)getTitle {
     
    [self.webview stringByEvaluatingJavaScriptFromString:@"alert(document.title);"];
}
-(void)openMyAlbum
{
    UIImagePickerController *vc = [[UIImagePickerController alloc]init];
    vc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentViewController:vc animated:YES completion:nil];
}
-(void)openMyCamera
{
    UIImagePickerController *vc = [[UIImagePickerController alloc]init];
    vc.sourceType = UIImagePickerControllerSourceTypeCamera;
    [self presentViewController:vc animated:YES completion:nil];
}
@end
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
JS代码压缩
WKWebView的使用和各种坑的解决方法(OC+Swift)
如何判断js引擎是javascriptCore还是v8引擎
从前端到全端:JavaScript逆袭之路
JSPatch
JavaScript与Objective
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服