IOS transfers value to JS class

Time:2020-11-27

IOS transfers value to JS class class class

Scene:

Web games written with cocos creator need to be connected to the app.

Try and difficulty:

1. Baidu’s IOS and JS call each other and pass value to each other. The web side is written with JS native, while the code of Cocos creator is the class class used.
2. After research, we found that IOS can only call the functions defined on the window object when calling JS functions to pass values. Then we tried to define functions outside the class to call IOS. We found that the functions defined in this way were defined on the window when running in the local environment, but not in the window object when running online, which led to the OC being useless.
3. For IOS value passing, quotation marks are not required for numeric type, but for string type. The joint debugging is very troublesome, so I have been looking for this problem for a long time
4. Next to 2, the definition function is to force the definition on the window, so that it can be found in the window object when the environment is online.

Here is the code:

JS:

//Initialization value
let iOSdata = "";

//The function called to OC needs to be defined on window with window
window.getInfo = function (data) {
    iOSdata = data;
};

//Class of Cocos Creator
cc.Class({
    extends: cc.Component,

    properties: {
    },


    // onLoad () {},

    start () {

    },

    // update (dt) {},
    
    doSomething:function(){
      //The obtained data is used in the class
      console.log(iOSdata)
    }
});

IOS:

\- (void)OCCallJS:(NSString\*)json{  
    //OC calls JS code  
    /\*\*  
     Corresponding JS code  
     function getAppData(str) {  
     asyncAlert(str);  
     document.getElementById("returnValue").value = str;  
     }  
     \*/  
     //Getinfo () is a method defined by JS
     //This is it!! Attention should be paid to the parameter type in getinfo()!! There has been a long time of joint debugging, although it is not a big problem.
    NSString \*jsStr = \[NSString stringWithFormat:@"getInfo('%@')",json\];  
    \[self.webView evaluateJavaScript:jsStr completionHandler:^(id \_Nullable data, NSError \* \_Nullable error) {  
        if (error) {  
            Dlog (@ "error:% @", error);  
        }else if(\[data isKindOfClass:\[NSDictionary class\]\]){  
              
        }  
    }\];  
}

Similarly, if you use other front-end frameworks, you just need to pay attention to the mandatory definition of the functions called by IOS in the window object. The code is very simple and self recording. I hope it will help you.
above.