[Objective-C에서 Javascript를 호출]


1. Objective-C에서 Javascript를 호출하는 방법 Objective-C에서 Javascript를 호출하는 방법은 stringByEvaluationJavascriptFromString: 메소드를 이용해 Javascript의 메소드를 호출하면 된다.



.m

@interface ViewController () 
@property (nonatomic, strong) UIWebView* webView;
@end


@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // WebView
    self.webView = [[UIWebView alloc] initWithFrame:self.view.frame];
    self.webView.delegate = self;
    [self.view addSubview:self.webView];
    
    NSString *path = [[NSBundle mainBundle] pathForResource:@"callTest" ofType:@"html" inDirectory:@""];
    NSURL *url = [NSURL fileURLWithPath:path];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [self.webView loadRequest:request];
       
    // call javascript button
    UIButton* callJavascriptBtn = [[UIButton alloc] initWithFrame:CGRectMake(200, 50, 150, 50)];
    [callJavascriptBtn setTitle:@"call javascript" forState:UIControlStateNormal];
    [callJavascriptBtn setBackgroundColor:[UIColor grayColor]];
    [callJavascriptBtn addTarget:self action:@selector(onCallJavascriptButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:callJavascriptBtn];
}

#pragma mark - Call javascript from objectiveC
- (void)onCallJavascriptButton:(id)sender {
    [self.webView stringByEvaluatingJavaScriptFromString:@"callJavascriptFromObjectiveC();"];
}
...
@end


callTest.html


<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8"/>
        <meta name = "viewport" content = "width = device-width"/>
        <title>Hybrid App</title>
        <script type="text/javascript">
            function callJavascriptFromObjectiveC() {
                alert('called javascript function by objective-c');
            }
        </script>
     </head>
    <body>
        <div id="container">     
            <h3>Call Javascript from Objective-C</h3>
        </div>
    </body>
</html>
</span>









[Javascript에서 Objective-C를 호출]

2. Javascript에서 Objective-C를 호출하는 방법은 커스텀 Scheme를 이용하는 방법이다. 

callTest.html에 button을 하나 만들고 버턴이 눌러지면 javascript에 구현한 callObjectiveCFromJavascript() 를 호출한다. 이 메소드 안에는 window.location를 이용해서 커스텀 scheme으로 이동하는 코드를 넣어둔다. 그러면 webView의 delegate 메소드의 webView: souldStartLoadWithRequest:navigationType 메소드를 호출하는데 이때 특정 메소드가 실행되게 구현하면 된다.




.m

@interface ViewController () 
@property (nonatomic, strong) UIWebView* webView;
@end


@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // WebView
    self.webView = [[UIWebView alloc] initWithFrame:self.view.frame];
    self.webView.delegate = self;
    [self.view addSubview:self.webView];
    
    NSString *path = [[NSBundle mainBundle] pathForResource:@"callTest" ofType:@"html" inDirectory:@""];
    NSURL *url = [NSURL fileURLWithPath:path];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [self.webView loadRequest:request];
}

#pragma mark - Call objectiveC from javascript
- (void)callObjectiveCFromJavascript {
    NSLog(@"called objective-c from javascript");
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request
 navigationType:(UIWebViewNavigationType)navigationType
{
    if ([[[request URL] absoluteString] hasPrefix:@"jscall:"]) {
        
        NSString *requestString = [[request URL] absoluteString];
        NSArray *components = [requestString componentsSeparatedByString:@"://"];
        NSString *functionName = [components objectAtIndex:1];
        
        if ([functionName isEqualToString:@"callObjectiveCFromJavascript"]) {
            [self performSelector:@selector(callObjectiveCFromJavascript)];
        }
        
        return NO;
    }
    return YES;
}
...
@end


callTest.html

<html>

    <head>

        <meta charset="utf-8"/>

        <meta name = "viewport" content = "width = device-width"/>

        <title>Hybrid App</title>

        <script type="text/javascript">

            function callObjectiveCFromJavascript(){

                window.location="jscall://callObjectiveCFromJavascript";

            }

        </script>

     </head>

    <body>

        <div id="container">     

            <h3>Call Objective-C from Javascript</h3>

            <button onclick="callObjectiveCFromJavascript();">Call Objective-C</button>

        </div>

    </body>

</html>



반응형