Interfacing between JavaScript and Objective-C on iOS devices

One method of communication between iOS and JavaScript involves creating fake URLs in JavaScript and appending a string as a parameter to Objective-C code. This URL is then parsed in the delegate method:

-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType

The return value from this process is sent by invoking the native method

stringByEvaluatingJavaScriptFromString
with the parameter callID.

However, I am interested in finding a way to directly call Objective-C methods from JavaScript on iOS, similar to how it can be done on Android without requiring additional JavaScript code to retrieve the return value. Our existing JavaScript code functions seamlessly with Android, but we are seeking a solution that will also meet AppStore requirements for iOS.

Answer №1

If you're looking to accomplish this task, there isn't a native method available. However, utilizing a tool like WebViewJavascriptBridge can help facilitate the process: https://github.com/marcuswestin/WebViewJavascriptBridge.

Even if there was an integrated solution in place, the lack of established standards would complicate things. In any case, achieving consistency with Android functionality is unlikely. Transitioning to Obj-C code involves transitioning away from web technology and onto platform-specific implementations that inherently differ across platforms.

Answer №2

To easily integrate JavaScript methods from objective C, follow these straightforward steps.

For a detailed guide, check out this resource and refer to the Apple Documentation

Answer №3

After thoroughly understanding your query regarding invoking an Objective-C method from Java script, I have found a comprehensive example in the official Apple Documentation:

Let's delve into a hypothetical scenario where we create an Objective-C address book class and make it accessible to JavaScript. Here is how the class definition may look like:

@interface MyAddressBook: NSObject {
}
+ (MyAddressBook *)addressBook;
- (NSString *)nameAtIndex:(int)index;
@end

Now, let's proceed with the code snippet to expose a MyAddressBook instance to JavaScript:

MyAddressBook *myContacts = [MyAddressBook addressBook];

id windowObject = [webView windowScriptObject];
[windowObject setValue:myContacts forKey:@"ContactList"];

Once you integrate these methods into JavaScript as detailed at the conclusion of this section, you will be able to interact with your address book through standard JavaScript functions.

For demonstration purposes, let's showcase how you can utilize the MyAddressBook instance in JavaScript. For instance, here's how you could display the name of a person at a specified index in your address book:

function displayPersonName(index) {
    var contactsBook = window.ContactList;
    var name = contactsBook.nameAtIndex_(index);
    document.write(name);
}

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 gather data from the M7/M8 chip even when the iPhone is in sleep mode within the CLVisit delegate method?

Is it possible to use the code within this method to retrieve data from the M7 sensor even when the app is not running? -(void)locationManager:(CLLocationManager *)manager didVisit:(CLVisit*)visit { } ...

The Android target is automatically updated after running cordova platform update

I'm currently in the process of upgrading my existing Cordova project from android version 3.6.4 to 3.7.2. Prior to the update, the target specified in the project.properties was set to 'android-19'. However, after the update, it changed to ...

Error message encountered when utilizing the Three.js JSONLoader: "'onLoad is not a function'."

I'm currently working on setting up a simple scene with Three.js to display an imported mesh rotating. I pieced together a couple of examples from the Three.js documentation and ended up with the code below: var scene, camera, renderer; var geometry, ...

What is the Vue.js equivalent of Angular's ng-container?

When working with Angular, you may come across a tag called ng-container which is used in the following way: <ng-container *ngIf="false">this won't be shown</ng-container> According to the Angular documentation: The Angular is a grou ...

Transforming PHP Variable Using Ajax

I have a variable called $type and I need it to be either month or year. This change should occur when a div is clicked. I attempted to use an onclick event with an ajax call. The ajax call and the variable are both in the same script (index.php). Within ...

Ways to eliminate the worldwide model in SAPUI5

I've been attempting to break down the global model without success. I have a filter button that's set up like this: navToSecond : function (oEvent){ var oObject = this.getView().byId("inp").getValue(); sap.ui.getCore().setModel( ...

Setting up the Angular2 library with a defaultExtension for systemjs configuration

Can I automate the setup of an npm repository for Angular2 to handle the systemjs config with default extensions? I'm currently working on ng2-orm and wondering if it's possible to streamline this process during npm installation. Although my pa ...

Alert: The `previousStep` prop on a DOM element is not recognized by React

import React, { Component } from 'react'; import ChatBot from 'react-simple-chatbot'; import { Switch, Route, BrowserRouter } from 'react-router-dom'; import Dropzone from 'react-dropzone'; class Form extends C ...

Contrast between sourcing a file from the current directory versus from the node_modules folder

Why does the typescript compiler accept importing from a JS file in the local directory but raises an error when importing from node_modules? Code: import { t2 } from "./t1.js" t2.hello(); import { mat4 } from "./node_modules/gl-matrix/esm ...

What is the best way to ensure that only one div is toggled at a time while using the toggle class function?

$(document).ready(function(){ $("#items").children().click(function(){ $(this).toggleClass('clicked'); }); }); .clicked { background-color:red; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></s ...

Frequently sending numerous UDP datagrams within a single thread can occasionally lead to micro bursts of packets

In our Android 7.0 application, we are working on sending UDP Datagrams over Wifi to a server. The size of each Datagram is 23 Bytes and they are sent at a frequency of approximately 15 milliseconds. We have implemented a Queue where we store ByteArrays. ...

Guide on integrating the @nuxtjs/axios plugin with Nuxt3

I'm trying to fetch API data from using this code: <template> <div> </div> </template> <script> definePageMeta({ layout: "products" }) export default { data () { return { data: &apo ...

JavaScript Compositions and Incorporations

Currently, I am delving into the world of compositions in Javascript and would like to confirm if my current approach is correct. I have been working on some exercises that follow this structure: class Animal { // constructor() { // } eat ...

What is the process for listing volumes on Mac OS X?

While I am not an expert in Mac OS X programming, I am currently working on a Qt application that requires information about storage devices, specifically hard drives and USB thumb drives. The desired outcome is to have a vector containing the following de ...

Experiencing memory issues with small programs in Node on macOS?

Currently, I am in the process of learning JavaScript and making use of node to execute JS programs directly from the terminal using this command: node program1.js The issue that I am encountering involves a simple JavaScript program that is supposed to ...

"Encountered an error while trying to fetch a PHP file using AngularJS $http.get - Error message

I am currently working with the file api.php which fetches necessary data from a database. require_once 'db.php'; $con = mysql_connect($host,$user,$pass); $dbs = mysql_select_db($databaseName, $con); $query=mysql_query("SELECT * FROM $tableName" ...

When a project sets useBuiltIns to 'usage', there is an issue with importing the library generated by Webpack

I am eager to create a versatile UI component library and bundle it with Webpack. However, I encountered an issue when trying to import it into another project that has useBuiltIns: 'usage' specified in the babelrc file. The import fails with the ...

Error encountered: EISDIR when using the "Cordova encrypted file plugin"

Recently, I encountered an issue with my ionic application built using ionic V1. A persistent EISDIR error keeps appearing whenever I try to build it. Upon investigating, I discovered that the culprit behind this error is the cordova-plugin-crypt-file. Dis ...

Update the text displayed in the Navigation Drawer

Is there a way to display text from the drawer header layout in the navigation drawer? protected void onCreate(Bundle savedInstanceState) { [...] NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigat ...

Using axios from a different directory on a file system

Creating a new folder named services which will contain all the axios actions for Vue. Here's what I have attempted: My save function save() { const CaseController = require("../services/gantt"); CaseController.create(this.data); }, My service f ...