IOS:ios和javaScript相互調用 oc和js

來源:互聯網
上載者:User

標籤:javascript   ios   objective-c   stringbyev   

文章來自:http://blog.csdn.net/intbird
相比android和js進行互動,ios和js進行互動是比較方便的;

android和js進行互動,請看這裡:

http://blog.csdn.net/intbird/article/details/42295453

android和js進行互動架構,看這裡:

http://blog.csdn.net/intbird/article/details/46461203

這裡看ios和js的互動

0.上個醜圖

1,oc調用js,超級方便,不論在代碼中的任何位置,
只需調用stringByEvaluatingJavaScriptFromString即可
代碼:

- (IBAction)webDemo:(id)sender {    NSString *name = [[UIDevice currentDevice]name];    NSString *js = [NSString stringWithFormat:@"showMessage(‘%@‘)",name];    [self.webView stringByEvaluatingJavaScriptFromString:js];}

2,js調用oc,大題是攔截每個url,對指定的schema進行攔截做相應的本地方法
代碼:

-(BOOL)webView:(nonnull UIWebView *)webView shouldStartLoadWithRequest:(nonnull NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{    NSString * url = request.URL.absoluteString;    if([url hasPrefix:@"intbird://"]){        NSString *urlConntet = [url substringFromIndex:@"intbird://".length];        NSArray *urlParams = [urlConntet componentsSeparatedByString:@"/"];        NSString* methodname = urlParams[0];        NSString* param = urlParams[1];        if([methodname isEqualToString:@"demoCallMethod"]){            [self performSelector:@selector(demoCallMethod:) withObject:param];        }        //# pragma clang diagnostic ignored "-Warc-performSelector-leaks"        //SEL method = NSSelectorFromString(methodname);        //[self performSelector:method withObject:param];        return NO;    }    return YES;}

4,重要ViewController代碼:

////  ViewController.m//  IntbirdJsInterface////  Created by intbird on 15/8/31.//  Copyright ? 2015年 intbird. All rights reserved.//#import "ViewController.h"#import <JavaScriptCore/JavaScriptCore.h>@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    NSURL *url = [NSURL URLWithString:@"http://127.0.0.1"];    NSURLRequest* request= [NSURLRequest requestWithURL:url];    [_webView loadRequest:request];    _webView.delegate = self;}//oc 調用 js;- (IBAction)webDemo:(id)sender {    NSString *name = [[UIDevice currentDevice]name];    NSString *js = [NSString stringWithFormat:@"showMessage(‘%@‘)",name];    [self.webView stringByEvaluatingJavaScriptFromString:js];}//js 調用 oc;-(BOOL)webView:(nonnull UIWebView *)webView shouldStartLoadWithRequest:(nonnull NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{    NSString * url = request.URL.absoluteString;    if([url hasPrefix:@"intbird://"]){        NSString *urlConntet = [url substringFromIndex:@"intbird://".length];        NSArray *urlParams = [urlConntet componentsSeparatedByString:@"/"];        NSString* methodname = urlParams[0];        NSString* param = urlParams[1];        if([methodname isEqualToString:@"demoCallMethod"]){            [self performSelector:@selector(demoCallMethod:) withObject:param];        }        //# pragma clang diagnostic ignored "-Warc-performSelector-leaks"        //SEL method = NSSelectorFromString(methodname);        //[self performSelector:method withObject:param];        return NO;    }    return YES;}-(void)demoCallMethod:(NSObject*)message{    UIAlertController * alert  = [UIAlertController alertControllerWithTitle:@"demoCallMethod"                                                                     message:(NSString*)message                                                              preferredStyle:UIAlertControllerStyleAlert];    UIAlertAction * alertCacel = [UIAlertAction actionWithTitle:@"Cacel"                                                          style:UIAlertActionStyleCancel                                                        handler:nil];    [alert addAction:alertCacel];    [ self presentViewController:alert animated:YES completion:nil];}-(void)webView:(nonnull UIWebView *)webView didFailLoadWithError:(nullable NSError *)error{    //JSContext *context = [webView valueForKey:@"documentView.webView.mainFrame.javaScriptContext"];    // NSString *alertStr = @"alert(‘alert called by oc‘)";    //[context evaluateScript:alertStr];}-(void)webViewDidFinishLoad:(nonnull UIWebView *)webView{}-(void)webViewDidStartLoad:(nonnull UIWebView *)webView{}-(void)webGoback:(id)sender{    if([_webView canGoBack]){        [_webView goBack];    }}-(void)webReload:(id)sender{    [_webView reload];}@end

5:廢話不多說了,直接上demo:
https://github.com/intbird/IOSIntbirdJsInterface

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

IOS:ios和javaScript相互調用 oc和js

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.