JS与OC的简单交互

js(javascript)与ios(Objective-C)相互通讯交互

地址:http://www.skyfox.org/javascript-ios-navive-message.htmljavascript

 

直接上代码
.m文件html

1java

2ios

3web

4框架

5atom

6url

7spa

8.net

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

#import "ViewController.h"

@interface ViewController () @property (weak, nonatomic) IBOutlet UIWebView*webView;

@end

@implementation ViewController

- (void)viewDidLoad 

{    

  [super viewDidLoad]; //经过本地html文件加载网页

  [self.webView loadRequest:[NSURLRequest requestWithURL:[[NSBundle mainBundle]URLForResource:@"test" withExtension:@"html"]]];

}

- (void)call 

{    //拨打电话    

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel://10086"]];

}

//是否容许加载从webview得到的请求

/* 

*该方法能够实现js调用OC 

*js和OC交互的第三框架可使用:WebViewJavaScriptBridge 

*/

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType

{    

//得到html点击的连接    

NSString *url = request.URL.absoluteString;    

//设置协议头    

NSString *scheme = @"zc://";    

//判断得到的连接前面是否包含设置头    

if([url hasPrefix:scheme])

{        

//切割字符串

NSString *methodName = [url substringFromIndex:scheme.length];

//调用打电话的方法

[self performSelector:NSSelectorFromString(methodName) withObject:nil];          

      return NO;    

 }else{            

      return YES;    

    }

}

html 文件

1.jpg

storyboard

2.png

运行结果

3.png

相关文章
相关标签/搜索