Exploring the capabilities of JavaScript on the iOS platform

Here is the code I've written for my iOS application:

webView             =   [[UIWebView alloc] init];
webView.delegate    =   self;

[webView loadHTMLString:@"<script type=\"text/javascript\" src=\"myFile.js\"></script>" baseURL:[NSURL fileURLWithPath:[NSBundle mainBundle].resourcePath]];

NSString* result =(NSString*)[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"myFunction(%d,%d,%d)", num1,num2,num3]];

NSLog(@"RESULT1 : %@", result);

And this is my JavaScript file, myFile.js:

function myFunction(a,b,c)
{
   return a*b*c;
}

However, I'm not getting any output in the result string. Can someone help me figure out what's wrong?

Answer №1

It is important to wait for the webViewDidFinishLoad: callback after the webview has finished loading.

You can implement the delegate method as shown below:

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    NSString* result = (NSString*)[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"myFunction(%d,%d,%d)", num1,num2,num3]];
    NSLog(@"RESULT1 : %@", result);
}

Additionally, make sure that your myFile.js is located under the Copy Bundle Resources instead of the Compile Sources section in Target->Build Phases.


If you are not familiar with JavaScript, the syntax for your JS function may appear unusual. The typical syntax is:

function myFunction(a,b,c)
{
   //Check if this alert gets called
   alert('Function called');
   return a*b*c;
}

Please review and verify the syntax.

I hope this information is helpful!

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

Stop users from being able to copy text on their smartphones' internet browsers

I am currently working on creating a competitive typing speed challenge using JavaScript. Participants are required to type all the words they see from a div into a textarea. In order to prevent cheating, such as copying the words directly from the div, o ...

When utilizing the yo angular-fullstack:endpoint, the message endpoint fails to produce the message.socket.js

Hey there, I've encountered an issue where the yo angular-fullstack endpoint shopPacket is not generating the shopPacket.socket.js file. I attempted to update the yo angular full stack generator, but unfortunately, the problem persists. yo angular-f ...

The system has encountered an issue: "EntityMetadataNotFound: Unable to locate metadata for the entity named 'User

Just wanted to reach out as I've been encountering an issue with my ExpressJS app recently. A few days ago, everything was running smoothly without any errors. However, now I'm getting a frustrating EntityMetadataNotFound: No metadata for "User" ...

The state of my React components keeps disappearing

Within my code, I have implemented a click event on the InterestBox to trigger updates in its appearance and alter the state of its parent container. However, despite inspecting the element using React Developer Tools and attempting API requests, the stat ...

Is there a way to efficiently eliminate the button label from my dataset without causing any disruptions to my chart

I am looking to remove a specific label from my chart, but whenever I try to do so, it impacts the entire functionality. var ctx = document.getElementById("CountryChart");<br> var myChart = new Chart(ctx, {<br><br> type: 'bar&ap ...

Bringing in a selection of functions as an object using ES6 imports

functions.js export const setA = () => {...} export const setB = () => {...} export const setC = () => {...} component.js import {setA, setB, setC} from 'functions' export class componentOne extends React.Component { constructor(p ...

AngularJS Treeview - Rearranging tree nodes

My journey with Angular is just beginning, and I managed to create a treeview following this example: jsfiddle.net/eu81273/8LWUc/18/ The data structure I've adopted looks like this: treeview1 = [ { roleName: "User ...

I have successfully implemented a click effect on one image and now I wish to apply the same effect to the remaining images

I've exhausted all my options and still can't crack this puzzle. Let me break it down for you: Upon entering the page, users are greeted with a collection of images each tagged with classes (for example, img01 and img02). When an image is clicke ...

Customize the color of the label and underline in a Reactjs material-ui TextField when the field input

https://i.stack.imgur.com/oJ2ah.png <TextField id="standard-full-width" label="Password" style={{ margin: 8 }} fullWidth margin="normal" placeholder="*******" /> Struggling to understand how to modify the color of the label ...

The route in my Node.js Express application appears to be malfunctioning

I am facing an issue with my app.js and route file configuration. Here is my app.js file: const express = require('express'); const app = express(); const port = process.env.PORT || 8080; const userRoute = require('./routes/user.route' ...

"Utilize the power of the ajaxform jQuery plugin to automatically reset form fields

Initially, I'd like to emphasize that this is an original inquiry. My predicament is as follows: I have a chatroom php script where I utilize the ajaxForm jQuery plugin to seamlessly send new messages without having to reload the entire page. Howev ...

Solving the Cross-Origin Resource Sharing problem in AngularJS

While using the http dependency in AngularJS and setting headers for CORS, I am encountering an error. Please check the console.log for more information on the error. The error message reads: "XMLHttpRequest cannot load . Response to preflight request doe ...

Assign Attribute to a Different Data Transfer Object

I have a query regarding my nestjs project - is it possible to assign a value Attribute to another Dto? Specifically, I'm looking to assign idData to the id in IsUniqueValidator. I attempted the following code but it resulted in 'undefined&apos ...

Issue with fixed sidebar on brief content

It's interesting how the sticky widget performs differently on long articles compared to short ones on my website. Here is an example of a long article where the sticky widget works well without any lag: . Now, let's take a look at a shorter art ...

Effortlessly fill dropdown menus with data from JSON files

I've been using this jQuery code successfully, but I recently needed to add 3 more field columns to the JSON. My goal is to have the HTML select drop-downs dynamically change based on the data from the previous drop-down. Additionally, my current jQue ...

Breaking the link

My tabulator column contains text with line breaks that are displayed properly. However, when I use the built-in URL formatter, the line breaks disappear. {title:"Title", field:"title", formatter:"textarea"}, https://i.sstatic.net/N8XZP.png I attempted ...

Trouble with highlighting the chosen menu item

I have been attempting to implement this code snippet from JSFiddle onto my website. Although I directly copied the HTML, used the CSS inline, and placed the Javascript in an external file, the functionality does not seem to be working properly. Feel free ...

Steps for creating a sleek vertical slider with transitional effects using JavaScript and HTML

Take a look at my code snippet: <table> <tr> <td onclick="shownav()">Equations of Circle <div id="myDownnav" class="sidenav"> <a>General Info</a> <a>In Pola ...

web browser editing tool

Do you know which library was utilized to create this JSON editor? https://i.sstatic.net/kGpGz.png You can find it at . The editor efficiently checks the syntax and shows errors when necessary. ...

Buttons in Highcharts

Is there a way to incorporate a button within a highcharts graph? I am working with a bar chart and would like to include a button on the left side of the label, similar to the example shown in this bar chart demo. I want the button to appear before the ...