How to use Javascript to communicate with Objective-c code?

后端 未结 1 1041
天命终不由人
天命终不由人 2020-12-17 06:28

In a native iPhone app, I use a UIWebView to load a web page.

I want to use JavaScript in the web page to communicate back with the Objective-C code, f

相关标签:
1条回答
  • 2020-12-17 06:41

    There is no "direct" way to do this, but you could utilize the UIWebViewDelegate and trap a link with a custom scheme, so in your markup, you'd write something like this:

    <a href="myapp://app_action?doSomething">Do Something</a>
    

    Then, in your UIWebViewDelegate's -webView:shouldStartLoadWithRequest:navigationType: method, write something like this:

    - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
        if([[[request URL] scheme] isEqualToString:@"myapp"]) { 
           SEL selector = NSSelectorFromString([[request URL] query]);
           if([self respondsToSelector:selector]) {
              [self performSelector:selector];
           } else {
              //alert user of invalid URL
           }
           return NO;
        }
        return YES;
    }
    
    0 讨论(0)
提交回复
热议问题