Sending an array from native IOS to JavaScript involves using a bridge or communication channel to

Currently developing an application that involves sending data from JavaScript to a native iOS controller. Wondering what is the best method for sending an array from the iOS controller to a JavaScript file.

Appreciate any guidance, thank you.

Answer №1

If you want to trigger your JavaScript function using an array as input, make sure to follow these steps:

NSArray *inputArray = @[@"apple", @"orange", @"banana"];
NSMutableArray *formattedArray = [NSMutableArray array];
// Wrap strings in quotes
for (NSString *item in inputArray) {
    [formattedArray addObject:[NSString stringWithFormat:@"\"%@\"", item]];
}
NSString *jsCallString = [NSString stringWithFormat:@"yourJSFunction([%@]);", [formattedArray componentsJoinedByString:@","]];
[webView stringByEvaluatingJavaScriptFromString:jsCallString]; // For UIWebView

This code will execute the JavaScript function

myJSFunction(["apple","orange","banana"]);

Answer №2

I suggest taking a look at this informative NSHipster article for further understanding.

In essence, it is recommended to utilize WKWebView and explore the concept of User Scripts for Injecting Behavior.

Snippet from the mentioned resource:

let script = "document.body.style.background = \"#777\";"
let userScript = WKUserScript(source: script, injectionTime: .AtDocumentEnd, forMainFrameOnly: true)

let userContentController = WKUserContentController()
userContentController.addUserScript(userScript)

let webViewConfig = WKWebViewConfiguration()
webViewConfig.userContentController = userContentController
self.webView = WKWebView(frame: self.view.bounds, configuration: webViewConfig)

It would help to provide more specific details when seeking assistance in the future.

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

Is it possible to display both UIMenuController and UIAlertController simultaneously?

Here is my approach: Message *message = self.messagesArray[indexPath.row]; UIAlertController *alertController = [UIAlertController alertControllerWithTitle:LocalizedString(@"FirstAction") ...

What steps can I take to avoid receiving an error stating that parameter 1 is not of type 'Node'?

I encountered the following error message: Uncaught TypeError: Failed to execute 'serializeToString' on 'XMLSerializer': parameter 1 is not of type 'Node'. I am unsure why this error is occurring. It works fine on localhost ...

Passing information from the created hook to the mounted hook in VueJS

How can I transfer data from the created function to the mounted function in VueJS? In my VueJS application, the code in my created function is as follows: created: function(){ $.getJSON({ url: 'static/timeline.json', success:function( ...

Issue in JavaScript on IE9: SCRIPT5022 error: DOM Exception - INVALID_CHARACTER_ERR (5)

I am encountering an error with the following line of code: var input2 = document.createElement('<input name=\'password\' type=\'password\' id=\'password\' onblur=\'checkCopy(th ...

Effortlessly move and place items across different browser windows or tabs

Created a code snippet for enabling drag and drop functionality of elements within the same window, which is working smoothly. var currentDragElement = null; var draggableElements = document.querySelectorAll('[draggable="true"]'); [].forEach ...

When using AngularJS, the templateUrl feature delays the initialization of the controller, causing issues with dependent code

Recently, I began experimenting with AngularJS and so far, everything seems to be going smoothly except for one small issue. Let's consider a scenario where I have two directives, with one directive relying on the other, like this: angular.module(&ap ...

Save unique pairs of keys and values in an array

I'm faced with extracting specific keys and values from a JSON data that contains a variety of information. Here's the snippet of the JSON data: "projectID": 1, "projectName": "XXX", "price": 0. ...

The routing navigate method is failing to direct to the desired component

For the past day, I have been struggling to find a solution to my issue but without success. The routing seems to be malfunctioning as it keeps showing the HTML content from app.component.html even when I try changing the path in the URL. Here is a snippe ...

Executing code on the server-side (back-end) using Javascript: A step-by-step guide

Imagine wanting to execute JavaScript on the server side instead of exposing the code to the client. For example: Starting with the JS native window Object from the browser. Performing all JavaScript processing in the backend by passing the window Object ...

Learning to master each individual jQuery method is an essential skill for any web developer

I'm working with the following function but $('input[id^="ProductId_"]').each(function () { it's giving me a different output than what I need. The desired result should be obtained from $('input[id^="ProductId_"]').cli ...

Is there a way to restore the face's original orientation after it has been rotated

Just to note, I am aware that this question has been asked before. However, the previous answers did not address my specific situation and requirements. Currently, I am developing a Rubik's cube using three.js. To achieve lifelike rotations, I am rot ...

What could be causing my YouTube code to malfunction with certain playlists?

Check out the first jsfiddle playlist here The Alum Songs Playlist is working perfectly, but unfortunately, the same code is not functioning for another playlist ID. View the second jsfiddle playlist here The Medical Animated Playlist is currently not w ...

The functionality of making Slim POST requests is currently not functioning as expected within the Ionic

An issue is arising with my app that makes calls to a REST API using POST and GET methods. The app I'm developing with Ionic works perfectly when emulated using the command: ionic serve --lab However, when running the app on an actual device, calls ...

Seamlessly transition between various states within a React component for a fluid user experience

I'm currently working on a simple component structured like this: var component = React.createClass({ render: function(){ if (this.props.isCollapsed){ return this.renderCollapsed(); } return this.renderActive() }, ren ...

Shift a Div to the left prior to stretching it out

I am trying to achieve a smooth leftward movement and expansion animation for a div. Currently, I am experimenting with class switching on click events to transition between the desired states. However, I am facing difficulty in making the element first mo ...

Reading JavaScript files using the HTML 5 File Reader

Currently, I am working on a feature that allows users to drag and drop a folder containing JavaScript files into an HTML5 page. Here is the code snippet for my implementation: $scope.files = []; //Establish dropzone var dropbox; dropbox = document.getEle ...

Build an API for generating albums in an iOS Photostream

We've developed a photo capture application and are looking to share the images through photostream directly from our app. Unfortunately, it seems that there isn't an API available to support this feature since iOS 6 when Apple introduced photo s ...

Ensuring interoperability of encryption between Obj-C and VB.Net

There are approximately 100,000 different potential methods for encrypting a string. While standards like AES, CBC, and PKCS7 simplify the process, issues with IVs still exist. Additional factors such as salts, encoding, etc. are discussed on www.Crypto.St ...

Searching through a JSON object for nested objects within objects

Currently, I have some data structured as follows: var items = [ { "id" : 1, "title" : "this", "groups" : [ {"id" : 1, "name" : "groupA"}, {"id" : 2, "name" : "groupB"} ] }, { "id" : 2, "title" : "that", ...

Access Sharepoint from an external site

Looking for assistance with a SharePoint list containing columns for Name, Position, Office, and Salary. Upon logging in with specific credentials to the SharePoint website, I need to retrieve all items from the list and showcase them on my own website. ...