iOS native vs. H5 interactive Wkwebview

Source: Internet
Author: User

First, native and H5 page interaction mode

    1. The token is placed in Wkwebview's cookie after login. In the future Wkwebview can also sync the native app login status.

The following code @ "Document.cookie = ' uid=%@ ';d ocument.cookie = ' Client=app ';d ocument.cookie = ' token=%@ '" is delivered according to the cookie format of your project.

1     nsstring *js = @ "function ClearCache () {localstorage.setitem (' fundtype ', null); Localstorage.setitem (' Fundtypeindex ', null);} ClearCache (); "; 2     nsstring *cookie = 3     [NSString stringwithformat:@ "document.cookie = ' uid=%@ ';d ocument.cookie = ' CLIENT=App '; Document.cookie = ' token=%@ ' ", 4      [user_default objectforkey:kuseruid] = = Nil @" ": [User_default Objectforkey: Kuseruid],[user_default Objectforkey:kusertoken] = = nil [email protected] "": [User_default Objectforkey:kusertoken]]; 5     Wkuserscript *cookiescript = [[Wkuserscript alloc] 6                                   initwithsource:cookie 7                                   injectiontime: Wkuserscriptinjectiontimeatdocumentstart 8                                   Formainframeonly:yes]; 9     [Self.configuration.userContentController adduserscript:cookiescript];10     [self reloadfromorigin];

2. Review the page elements in Wkwebview, extract the JS code called by the login button in the Wkwebview landing page (as far as possible to JS developers)

Then through the code to execute JS: The parameters passed to JS. Let Wkwebview execute Js,wkwebview on the landing.

The following code @ "function ClearCache () {localstorage.setitem (' fundtype ', null); Localstorage.setitem (' Fundtypeindex ', null);} ClearCache (); "is a pure JS code, IOS programs can be used directly.

1 NSString *js = @ "function ClearCache () {localstorage.setitem (' fundtype ', null); Localstorage.setitem (' Fundtypeindex ') , null);} ClearCache (); "; 2             [Self.basewebview evaluatejavascript:js completionhandler:^ (id _nullable Other, nserror * _nullable error) {3             }];

3, through this method, intercept H5 page will be requested page address, to do the native corresponding operation. Here can let Wkwebview jump to "Hello://uid=123_token=321" way to tell the native, JS passed 2 parameters: uid=123 token=321 (note, here is the beginning of Hello, Can be written as you discussed) then by: Decisionhandler (Wknavigationactionpolicycancel);

Do not let Wkwebview jump to "hello://uid=123_token=321". To do the things we really want to do.

 1-(void) WebView: (Wkwebview *) WebView decidepolicyfornavigationaction: (wknavigationaction *) navigationaction Decisionhandler: (void (^) (wknavigationactionpolicy)) decisionhandler{2 NSString *str = Navigationaction.request.url.absolutestring;//gets the currently requested URL 4 if ([str isequaltostring:@ "https://m.cgjr.com/"] & & Self.viewController.tabBarController.selectedIndex! = 0) {5 Decisionhandler (wknavigationactionpolicycancel) ; 6 [Self.viewController.tabBarController setselectedindex:0]; 7} 8 if ([str isequaltostring:@ "https://m.cgjr.com/site/login.html"] && Self.viewController.tabBarControl Ler.selectedindex = = 0) {9 decisionhandler (wknavigationactionpolicycancel); Uistoryboard *SB = [UIStory Board storyboardwithname:@ "Cgtzlogin" bundle:nil];11 cgtzloginviewcontroller *NAVC = [SB Instantiateviewcontroller withidentifier:@ "Cgtzloginviewcontroller"];12 navC.tabBarItem.title = @ "Login"; [Self.viewcontroller PresENTVIEWCONTROLLER:NAVC animated:yes completion:^{14}];15 [Self.viewController.tabBarController setselecte Dindex:0];16}17 if ([str isequaltostring:@ "https://m.cgjr.com/site/login.html"] && Self.viewController.ta  Bbarcontroller.selectedindex = = 1) {Decisionhandler (wknavigationactionpolicycancel); Uistoryboard *SB = [Uistoryboard storyboardwithname:@ "Cgtzlogin" bundle:nil];20 cgtzloginviewcontroller *navC = [SB instantiateVie wcontrollerwithidentifier:@ "Cgtzloginviewcontroller"];21 navC.tabBarItem.title = @ "Login"; [Self.viewcontro Ller PRESENTVIEWCONTROLLER:NAVC animated:yes completion:^{23}];24 [Self.viewController.tabBarController s Etselectedindex:1];25}26 if ([str isequaltostring:@ "https://m.cgjr.com/site/login.html"] && Self.viewcont Roller.tabBarController.selectedIndex = = 2) {Decisionhandler (wknavigationactionpolicycancel); uistory board *SB = [UistoryboarD storyboardwithname:@ "Cgtzlogin" bundle:nil];29 cgtzloginviewcontroller *NAVC = [SB instantiateviewcontrollerwith identifier:@ "Cgtzloginviewcontroller"];30 navC.tabBarItem.title = @ "Login"; [Self.viewcontroller Presentvie WCONTROLLER:NAVC animated:yes completion:^{32}];33 [Self.viewController.tabBarController setselectedindex : 2];34}35 Decisionhandler (Wknavigationactionpolicyallow); 36}

4. Use JS to directly call OC method on iOS platform

In the Cocos2d-js v3.0 RC2, like on Android JS call Java, COCOS2D-JS also provides a way to call Objective-c on iOS and Mac directly, the sample code is as follows:

    JSB.  Reflection.  Callstaticmethod(classNamemethodnmaearg1arg2...);      

In the jsb.reflection.callStaticMethod method, we can directly call OC's static method by passing in the class name of OC, method name, parameter, and can get the return value of OC method.

Class
    • The class name in the parameter only needs to pass in the class name in OC, unlike Java, where the class name does not require a path. For example, if you create a new class under the project, NativeOcClass as long as you introduce him to the project, then his class name is NativeOcClass that you don't need to pass in its path.
1 Import <foundation/foundation.h>2     @interface nativeocclass:nsobject3     + (BOOL) callnativeuiwithtitle :(NSString *) title andcontent: (NSString *) content;4     @end
Method
    • The JS to OC reflection only supports static methods of classes in OC.
    • Method name comparison It is important to note that we need to pass in the full method name, especially if a method has parameters, you need to bring his * *:* *. According to the above example. The method name at this time is **callnativeuiwithtitle:andcontent:**, do not miss their * *:* *.
    • If it is a function without parameters, then he does not need * *:* *, the following code, his method name is callNativeWithReturnString , because there is no parameter, he does not need * *:* *, and OC method of the same wording.

1 + (NSString *) callnativewithreturnstring;

Using the example
    • The following example code calls the above NativeOcClass method, which we only need to invoke in the JS layer:
1     var ret = Jsb.reflection.callStaticMethod ("Nativeocclass", 2                                                "Callnativeuiwithtitle:andcontent:", 3                                                " Cocos2d-js ", 4                                                " yes! a Native UI from Reflection ");

    • Here is the implementation of this method in OC, which can be seen to pop up a native dialog box. and title content set it to the parameter you passed in, and return a Boolean return value.
1     + (BOOL) Callnativeuiwithtitle: (NSString *) title andcontent: (NSString *) content{2         uialertview *alertview = [ [Uialertview alloc] initwithtitle:title message:content delegate:self cancelbuttontitle:@ "Cancel" OtherButtonTitles: @ "OK", nil];3         [Alertview show];4         return true;5     }

    • At this point, you can ret accept the return value (TRUE) returned from OC in.
Attention

In the OC implementation, if the parameters of the method need to use float, int, bool, use the following types to convert:

    • Float,int please use NSNumber type
    • BOOL use bool type.
    • For example, the following code, we pass in 2 floating-point numbers, and then calculate their merge return, we use nsnumber instead of int, float to go as the parameter type.
1 + (float) Addtwonumber: (NSNumber *) NUM1 and: (NSNumber *) num2{2     float result = [Num1 floatvalue]+[num2 floatvalue];3     return Result;4}

    • The current parameters and return values support int, float, bool, string, and the remaining types are temporarily unsupported.

5, Wkwebview Unique, with UIWebView jscontext similar wkscriptmessage

JS end so called: Red part

1 function onLoaded () {2         changeimagesrc (); 3     var allimage = document.getelementsbyclassname ("Img-cache"); 4         allimage = Array.prototype.slice.call (allimage, 0); 5         var imageurlsarray = new Array (); 6         Allimage.foreach (function (image) {7             var esrc = Image.getattribute ("ESRC"); 8             if (ESRC) {9             var newlength = Imageurlsarray.push (ESRC);             }11         });         window.webkit.messageHandlers.  Xxxapp. PostMessage ({"Key": "Getimageurlarr", "Getimageurlarr": Imageurlsarray});}onloaded ();

When creating Wkwebview:

1         wkwebviewconfiguration *configuration = [Wkwebviewconfiguration new]; 2         configuration.selectiongranularity = Wkselectiongranularitycharacter; 3         Configuration.usercontentcontroller   = USERVC; 4         [Configuration.usercontentcontroller Addscriptmessagehandler:self name:@ "xxxapp"]; //Here is the identifier for iOS side 5         wkwebview * WebView                   = [[Wkwebview alloc]initwithframe:cgrectmake (0, 0, Kscreenwidth, kSCreenHeight-64) configuration:configuration]; 6         webview.navigationdelegate            = self, 7         webview.uidelegate                    = self, 8         nsurl *url                            = [Nsurl URLWithString:self.urlString]; 9         nsmutableurlrequest *request          = [[Nsmutableurlrequest alloc]initwithurl:url];10         [WebView Loadrequest:request];

Proxy methods that need to be implemented:

1-(void) Usercontentcontroller: (Wkusercontentcontroller *) Usercontentcontroller didreceivescriptmessage: ( Wkscriptmessage *) Message {2     nsdictionary *datadic = message.body; 3     if ([datadic[@ "key"] isequaltostring:@ "Getimageurlarr"]) {//based on key value pairs of key, determine which piece of code to call 4         nsarray *imagearr = datadic[@ " Getimageurlarr "]; 5         if (Imagearr! = nil) {6//            JS passed in an array we've got it! , go do what you want to do! 7         } 8     } 9     if ([datadic[@ "key"] isequaltostring:@ "imagedidclicked"]) {10//        [Self imagedidclicked:datadic[@ "imagedidclicked"]];11     }     if ([datadic[@ "key"] isequaltostring:@ "imagesdownloadcomplete"]) {   19} }

Wkwebview Related references: http://www.henishuo.com/wkwebview-js-h5-oc/

(Swift) http://www.henishuo.com/wkwebview-js/

Wkwebview API for all related classes: http://www.henishuo.com/wkwebview-objc/

There are 5 ways to interact, and there's always one for you.

iOS native vs. H5 interactive Wkwebview

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.