Executing a callback function in Swift using JavaScriptCore

Struggling to figure out how to call a Javascript Function with a callback from Swift, but it's not working as expected.

Here's what I have:

Javascript:

global.calculateWithCb = function(temp,cb){
    cb(5 * temp)
}

global.calculate = function(temp) {
    return 5 * temp
}

Swift:

let context = JSContext()
let scriptURL = NSURL(fileURLWithPath: String("XXX/bundle.js"))
let script : String = try String(contentsOfURL:scriptURL, encoding: NSUTF8StringEncoding)

var jsSource: String! = script
jsSource = "var window = this; \(jsSource)"
context.evaluateScript(jsSource)

let calculate = context.objectForKeyedSubscript("calculate")
let output = calculate.callWithArguments([40]).toNumber()

Although the calculate function is functioning correctly, I'm stuck on how to pass a block as a callback argument. I've searched extensively online for a solution but haven't found any helpful hints. Can anyone provide guidance on how to achieve this?

Answer №1

In order to pass a Swift block to a JSValue as an argument, you must first manually initialize the JSValue with a @convention(block) block.

let testBlock : @convention(block) (JSValue?) -> Void = { calledBackValue in
    print("calledBackValue:", calledBackValue)
}
let callback = JSValue.init(object: testBlock, in: context)
// ...
jsFunctionToCallWithCallback.call(withArguments: [42, callback])
var theJSFunction = function(val, callback) {
    // Do smt...
    callback(val);
}

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

What is the best way to transfer the "user" object from TopBar.js to App.js in my project?

In my project, TopBar.js functions as an AppBar component responsible for handling user authentication. When a user logs in, I receive an object called "user". My goal is to export this "user" object to App.js. If I am successful in exporting it to App.js ...

Arranging and moving list elements without the use of jQuery UI (or any jQuery libraries at all?)

I have been searching for a JavaScript plugin that offers the same functionality as jQuery UI Sortable, which is the ability to drag and drop items to reorder them. In my case, these items are <li> tags. I prefer not to use jQuery UI because it is h ...

What is causing my code to not store all the rows from the array into the table?

I've encountered an issue with my Swift function that is designed to save the content of an array of dictionaries into a table. Even though I have 19 dictionaries in the array, only two of them seem to be successfully saved in the database table. Desp ...

Tips on building a blog using solely index.html, style.css, and script.js files

Looking for inspiration for blog listing pages? Check out some examples like: HubSpot's marketing blog or iGoMoon's blog. I'm trying to figure out where I should start. Should I begin with the first line of code? Or can I import sample code ...

Update the default base URL configuration for Axios

My axios configuration looks like this: const configAxios = { baseURL: 'http://127.0.0.1:8000/api', timeout: 30000, }; Vue.prototype.$axios = axios.create(configAxios) When making a call inside my component, I use the following syntax: this ...

Having difficulty setting up multiple buttons to share the same function in jQuery using HTML

After clicking a button, my code dynamically adds content to a div and inserts buttons with names like "teamReq_"+index+"_AddYear" into the document (where index is a number retrieved from a hidden input field). If these buttons are spammed, multiple divs ...

How to Conceal the Search Bar in jQuery DataTables

I am having trouble hiding the default search bar in DataTables. Despite trying solutions from this thread, using bFilter:false completely disables filtering, rendering my search boxes in the footer non-functional. I have created a jsfiddle demonstration. ...

What could be the reason my black overlay doesn't show up when the button is clicked?

Attempting to craft a pop-up window on my own, I encountered an issue. Upon pressing the button, instead of the anticipated pop-up appearing and darkening the background below it, the entire page freezes with no sign of the pop-up box. If I eliminate the ...

Creating a multi-page form in AngularJS with Tab navigation

Hello, I am currently working on implementing a multi-stage form using AngularJS Tabs. Instead of using routes in this application, I am trying to achieve the desired functionality solely through tabs. app.controller('createProjectController', [ ...

An Ajax call navigates to the index.html page

Could you please assist with an issue I am facing? I have written the code below to make an ajax request to a specific link. However, instead of executing the ajax call using a POST request, the page is being redirected to index.html with the link in the ...

Add the Selected Value to the Title

Is there a way to dynamically add the selected value from each select element to its corresponding heading without requiring user interaction? I need this to happen as soon as the page loads. Here is an example in a jsfiddle https://jsfiddle.net/dqfvyvdt/2 ...

Using Vue to Bring in External JavaScript Files

If I have 2 JavaScript files located in the 'resources/assets/js' directory, named 'app.js' and 'ext_app.js', what could be the issue? Within 'ext_app.js' file, there is a function defined like this: function testF ...

What is the best way to organize JSON files data in a specific sequence?

I successfully converted 3 JSON files into an HTML page using AngularJS. Here is the code I used: Factory code app.factory('myapp', ['$http', function($http) { function getLists() { var tab = ['url1', 'url2 ...

Creating interactive comments in Vue 3 using dynamic rendering

Is there a way to properly display a dynamic comment in Vue 3? I attempted using v-html, but it's not working as expected in my scenario. Here is the example: https://i.sstatic.net/ddX39.png <template> <!-- Method 1: not displaying correctl ...

Is there a way to separate a string using two different delimiters?

Here is my code snippet : <template> ... <p v-for="club in clubs">{{club}}</p> ... </template> <script> export default { data: () => ({ clubs: '' }), mounted () { let dataClub = "- ...

Default modal overlay closure malfunctioning; encountering errors when manually managed through jQuery

A custom overlay has been designed and implemented. <div class="overlay modal" id="11"> <div class="background-overlay"></div> <div class="description"> <div class="hidden-xs"> <img src=' ...

Incorporating a Streamlit Application into an Established React.js Project via an iFrame

I am in the process of incorporating a Streamlit app into my existing React.js application to take advantage of its data analysis and visualization features. Can this integration be accomplished using an iFrame? Has anyone successfully embedded a Streamlit ...

Encountering difficulties with updating an object in Angular

Currently, I have the ability to generate objects and store them in a rails database using a json api. The application is a basic todo list where adding an object places it into the todo list above the input fields. Furthermore, I can access all objects on ...

Why am I encountering a type error in NodeJS when utilizing the ping module?

I'm currently working on creating a simple app for pinging an IP address. The HTML form I've created has one input field for the IP address, which is then sent to NodeJS for processing. I am utilizing the ping module to retrieve the results. Ever ...

Guide on merging non-modular JavaScript files into a single file with webpack

I am trying to bundle a non-modular JS file that uses jQuery and registers a method on $.fn. This JS must be placed behind jQuery after bundling. Here is an example of the structure of this JS file: (function($){ $.fn.splitPane = ... }(JQuery) If y ...