Call the javascript function (provided as a parameter) from native iOS code

I am grappling with a JavaScript function structured like this.

function getState(){
   return "Hello";
}

var cryptico = (function() {

var my = {};

    my.generateRSAKey = function(passphrase, bitlength)
    {
        Math.seedrandom(sha256.hex(passphrase));
        var rsa = new RSAKey();
        rsa.generate(bitlength, "03");
        return rsa;
    }

}());

If the function were declared outside, calling it would be simple.

NSString *jsPath = [[NSBundle mainBundle] pathForResource:@"cryptico" ofType:@"js"];

NSString *scriptString = [NSString stringWithContentsOfFile:jsPath encoding:NSUTF8StringEncoding error:nil];

JSContext *context = [[JSContext alloc] init];
context = [[JSContext alloc] init];
[context evaluateScript:scriptString];

JSValue *test10 = context[@"getState"];
JSValue *test11 = [test10 callWithArguments:@[]]; //will be Hello

The challenge arises when attempting to invoke something stored within a variable. Despite several attempts using various methods, I have been unable to achieve the desired outcome.

Answer №1

In the realm of JSValue Apple Documentation:

When transitioning between an Objective-C block (Swift clousre) and a javascript function, the recommended method is to utilize

valueWithObject:inContext:

for converting to a JSValue, as demonstrated in your code snippet, and

toObject

for converting to its specific type, which in this scenario happens to be a block. So initially give a shot at

[test10 toObject];

followed by storing it as a block, and subsequently executing the block normally

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I dynamically insert the highest number from a specific group of numbers in a table using JavaScript?

PROBLEM: I am currently working on a loop to insert values into a MySQL DB. Within this loop, I am generating a MAX(num) to retrieve the highest number in each selected store group. After that, the application creates a list with various values conta ...

How to retrieve an unknown JSON key in Vue.js when using v-for loop?

I have developed a code analysis tool and I am looking to display my JSON data in a Vue table. The challenge is that I need the JSON key, which represents the package/file name of the directory whose data I want to showcase. Below is an excerpt of the JSO ...

Retrieving multiple selected row values using an ASP Repeater

Within my repeater, I have three values bound: a visible "User Name" column, a visible "Business" column, and a hidden field called "UserId". My goal is to implement the following functionality: when a row is clicked, it should highlight in a different c ...

Ways to invoke jQuery(this) within an anchor tag's onclick event handler

My task involves working with HTML code and I need to apply a class name to the parent li tag using jQuery. Here is the HTML code snippet: <ul> <li><a onclick="setSelectedTestPlan();" href="javascript:void(0);">New Test</ ...

Activating the Play button to start streaming a link

Recently delved into the world of Ionic 4 and Angular, so definitely a beginner :) Purchased a UI Template from code canyon but didn't realize I needed to code the music player part. Been trying to get a music stream playing but no luck. Came across ...

The PHP Comet feature is causing the page to experience delays in reloading

Hello, I am working on implementing comet functionality using PHP and jQuery. The comet starts with every page load, but this seems to be causing a significant delay in loading any page on the website, taking about 10 seconds. It appears as though the page ...

Is it possible to simultaneously run two Node.js projects on Windows?

Is it possible to run two Node.js projects on a Windows operating system? If so, what is the process for doing that? If not, can I run two Node.js projects on a dedicated host instead? ...

Change ES6 JavaScript to ES5 standard

Is there a way to transform this code snippet from other questions into ES5 format? I am attempting to extract data from a JSON array. var match = function(query, input) { return input.filter(function(entry) { return Object.entries(query).every(fun ...

Error encountered due to unidentified JSX syntax within div element

**** When I check the terminal, this is what I see **** ./src/card.js Line 9:9: Parsing error: Unterminated JSX contents 7 | <h2>john doe</h2> 8 | <p><a href="/cdn-cgi/l/email-protection" cl ...

Is there a way to execute jQuery code only after AngularJS has finished rendering all its components?

My goal is to display or hide my chart div based on different pages (Add, Edit, Save As). This functionality should be controlled by a checkbox - when the checkbox is checked, the div is displayed, and when it is unchecked, the div is hidden. On the Add ...

Do not remove data from the parent table while it is still being referenced in the child table

There are two tables in question - the Nationality table (parent) and the Employee table (child). The requirement is to display a message when a user attempts to delete data from the parent table that is currently being used by the child table. The message ...

Utilize the sendKeys method to input text and save the entered value in

Currently, I am using WebdriverJS to interact with a form. In my test, I want to open the form, fill in a field using sendKeys, and then store this value in a variable. Here is the code snippet: driver.findElement(By.xpath("//a[contains(text(),'Añad ...

Refresh the PartialView only after clicking submit

I am struggling with updating only the contents of my partial view after clicking an input type="submit button. My goal is to refresh just the partial view and update it with the updated model from the controller code, without refreshing the entire page. S ...

Encountering an error with $mdDialog.alert

I am attempting to activate an Alert Dialog using Angular Material Design. Within my controller, I have: angular.module('KidHubApp') .controller('ActivityCtrl', ['$scope','$meteor', '$stateParams', &apo ...

Changing the color of a progress bar in Bootstrap based on a specific percentage level

var elem = document.getElementById("progress-bar"); var progress = 75; elem.style.width = 80 + '%'; if (progress > 80) { elem.style.background = "red"; } #myProgress { height: 5px; } #progress-bar { w ...

Querying for multiple images using Gatsby's GraphQL functionality

I need help querying for multiple specific images with GraphQL in Gatsbyjs. I initially attempted the following: file(relativePath: {eq: "images/front.jpg"}) { id } file(relativePath: {eq: "images/front2.jpg"}) { id } This is resulting in an error ...

Is it better to set the height of Material UI CardMedia based on aspect ratio or use vh

const customStyles = createStyles({ media: { height: 183 } }); <CardMedia className={classes.media} image="pic.jpg" /> Instead of setting the size in pixels, is there a method to adjust it based on an aspect ratio? For instanc ...

What is the rationale behind using `./routes` instead of just `/routes` in express routes?

In most instances that I've come across, the app.js file typically uses the require function with the path of ./. I'm curious as to why we can't simply use /. For example, why wouldn't the following code work: var express = require(&ap ...

How can I create distinct edges that intersect the surfaces of other objects in THREE.js?

Currently, I'm involved in a three.js project where I need to display all edges of geometries, even when those edges intersect with surfaces of other objects. Below is the code snippet that showcases my dilemma: var camera, scene, renderer, materi ...

Using JQuery to append elements and then locate them with the find method does not produce the expected

Hey there, I'm having trouble inserting one DOM element into another. It's something I've done many times before successfully, but for some reason it's not working this time and I can't figure out why. Currently, I am using an Aja ...