JS与iOS之间的通信

Stella981
• 阅读 761

JS与iOS之间的通信,主要运用两个方法:(PhoneGap框架也是基于此原理)

1、UIWebView的 stringByEvaluatingJavaScriptFromString方法

2、UIWebViewDelegate的

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

示例:

上部分是一个UIWebView,实现UIWebViewDelegate

JS与iOS之间的通信

[plain] view plain copy print ?

  1. - (void)viewDidLoad

  2. {

  3. [super viewDidLoad];

  4. NSString *path = [[NSBundle mainBundle] pathForResource:@"jm/info" ofType:@"html"];

  5. NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]];

  6. [self.webView loadRequest:request];

  7. }

    • (void)viewDidLoad { [super viewDidLoad]; NSString *path = [[NSBundle mainBundle] pathForResource:@"jm/info" ofType:@"html"]; NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]]; [self.webView loadRequest:request]; }

[plain] view plain copy print ?

  1. #pragma mark - UIWebViewDelegate

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

  3. {

  4. if([request.mainDocumentURL.relativePath isEqualToString:@"/getInfo/name"])

  5. {

  6. NSString *info = [[UIDevice currentDevice] name];

  7. NSString *js = [NSString stringWithFormat:@"showInfo(\"name\",\"%@\")",info];

  8. [self.webView stringByEvaluatingJavaScriptFromString:js];

  9. return false;

  10. }

  11. if([request.mainDocumentURL.relativePath isEqualToString:@"/getInfo/systemVersion"])

  12. {

  13. NSString *info = [[UIDevice currentDevice] systemVersion];

  14. NSString *js = [NSString stringWithFormat:@"showInfo(\"systemVersion\",\"%@\")",info];

  15. [self.webView stringByEvaluatingJavaScriptFromString:js];

  16. return false;

  17. }

  18. return true;

  19. }

#pragma mark - UIWebViewDelegate

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    if([request.mainDocumentURL.relativePath isEqualToString:@"/getInfo/name"])
    {
        NSString *info = [[UIDevice currentDevice] name];
        NSString *js = [NSString stringWithFormat:@"showInfo(\"name\",\"%@\")",info];
        [self.webView stringByEvaluatingJavaScriptFromString:js];
        return false;
    }
    if([request.mainDocumentURL.relativePath isEqualToString:@"/getInfo/systemVersion"])
    {
        NSString *info = [[UIDevice currentDevice] systemVersion];
        NSString *js = [NSString stringWithFormat:@"showInfo(\"systemVersion\",\"%@\")",info];
        [self.webView stringByEvaluatingJavaScriptFromString:js];
        return false;
    }
    return true;
}

JS代码:

[html] view plain copy print ?

  1. <html>

  2. <head>

  3. <title>city</title>