[iOS] How to use JS to call iOS functions in WebApp

Source: Internet
Author: User

Implementation features: Click on the HTML tag, via JS call the internal iOS native function


Basic Flow:



First look at the Web, we add an onclick event to the H1 tag so that it modifies the current URL after being clicked.

HTML code in the Web:




In iOS, drag webview First, access localhost, and then listen to the URL jump through the WebView delegate event and intercept the jump.

That is, at the time of the onclick, the normal browser gray jumps to that URL, but in iOS this webview inside, this jump transfer is intercepted,

In this way, you can cleverly implement the native code of JS calling iOS:


dwviewcontroller.m//darewayapp////Created by what on 14-6-3.//Copyright (c) 2014 Dareway. All rights reserved.//#import "DWViewController.h" @interface Dwviewcontroller () @property (weak, nonatomic) Iboutlet  UIWebView *mywebview; Main Page @end@implementation dwviewcontroller-(void) viewdidload{[Super viewdidload];//do no additional setup after LOA                Ding the view, typically from a nib. Fit iOS6 status bar if ([[[[Uidevice Currentdevice] systemversion] Floatvalue] >= 7) {_mywebview.frame = Cgrectmak    E (0,20,self.view.frame.size.width,self.view.frame.size.height-20);    }//load the developed URL nsurl *url =[nsurl urlwithstring:@ "http://localhost"];    Nsurlrequest *request =[nsurlrequest Requestwithurl:url];    [_mywebview setdelegate:self]; [_mywebview loadrequest:request];} Each request in the webpage is triggered-(BOOL) WebView: (UIWebView *) WebView shouldstartloadwithrequest: (nsurlrequest *) request Navigationtype: (Uiwebviewnavigationtype) navigationtype{//per jumpWait for the URL if ([Request.mainDocumentURL.relativePath isequaltostring:@ "/getinfo/why"]) {NSLog (@ "why");    return NO; } return YES;    -(void) didreceivememorywarning{[Super didreceivememorywarning]; Dispose of any resources the can be recreated.} @end


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.