Utilizing Callback Functions within Swift Modules in React Native

I'm currently working on creating a native swift module that includes a function I need to call in my javascript code. At the moment, I have three key files for this setup: module.swift, module.m, and the bridging header.

This is what MyModule.swift looks like:

import Foundation

@objc(MyModule)
class MyModule: NSObject {

  @objc func callbackMethod(callback: RCTResponseSenderBlock) -> Void {
     let resultsDict = [
     "success" : true
     ];

    callback([NSNull() ,resultsDict])
  }

}

Now, let's take a look at MyModule.m:

#import <Foundation/Foundation.h>

#import <React/RCTBridgeModule.h>
#import <React/RCTEventEmitter.h>

@interface RCT_EXTERN_MODULE(MyModule, NSObject)

RCT_EXTERN_METHOD(callbackMethod:(RCTResponseSenderBlock)callback)

@end

Here's a snippet from the bridging header:

#import React/RCTBridgeModule.h

#import React/RCTEventEmitter.h

To make use of this functionality in JavaScript, here's how you can call it:

const { MyModule } = require('NativeModules');
MyModule.callbackMethod((err,r) => console.log(r));

The issue that arises upon running the project stems from the error message:

Exception 'callbackMethod:(RCTResponseSenderBlock)callback is not a recognized Objective-c method.' 

Despite following the documentation closely, I seem to be facing this problem. Any assistance or insights would be greatly appreciated!

Answer №1

There's been a recent update in the way we write the @objc section for methods.

Instead of:

@objc func callbackMethod(callback: RCTResponseSenderBlock) -> Void {
 let resultsDict = [
 "success" : true
 ];

callback([NSNull() ,resultsDict])

We now write it as:

@objc(callbackMethod:)
func callbackMethod(callback: RCTResponseSenderBlock) -> Void {
 let resultsDict = [
 "success" : true
 ];

callback([NSNull() ,resultsDict])

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

Importing a third-party JavaScript library in Angular 2 RC5: Utilizing Showdown Library

Struggling with the integration of Showdown as a vendor in my project. Whenever I compile, the browser console throws an error saying showdown is not defined. Since it's a vendor package, importing it directly into app.module.ts doesn't seem to b ...

Javascript is not fetching the value

Here is the code snippet I am working with: var categoryDetailId = $("#createEventForm-categoryDetail-idCategory").val(); and this link from my rendered page: After clicking the button, it returns NaN Update: I tried setting it manually, but it still ...

Is there a way to retrieve the io object within the io.sockets.on callback function?

My preference is to not alter my sockets method. I was hoping to be able to utilize the io object within the connected function. Could this be a possibility? function sockets (server) { const io = require('socket.io')(server); io.sockets.on ...

Initial value preselected for radio button

Is there a way to ensure that the Default radio button selected in the following code is always "Period"? Currently, when the page loads, none of the radio buttons are selected. <tr> <th valign="top" align="left"> Scope ...

Angular JS appears to be causing the DOM to freeze up while utilizing the ng-repeat directive to loop through

I have a current app where clicking a button triggers an $http request to fetch and return some data. The retrieved information is then used to update the $scope variables rows and columns, which are then looped through using ng-repeat. However, I've ...

Bug in ExtJS 4 causing the clickrepeater to be disabled when using the datepicker

I've developed a custom subclass of the DatePicker class. Within the update() method, I have implemented logic to disable the prevRepeater if the current month matches the month of the minDate property: me.prevRepeater.setDisabled(me.minDate &&am ...

What is the most effective way in MongoDB to insert data only if it does not already exist in the database?

Is there an optimal way to insert data into MongoDB only if it doesn't already exist in the table? The unique field for searching is hash, which is also indexed. router.post('/', async (req, res) => { try{ var id = null const ...

Switch between Coordinated Universal Time and a designated time zone using the New Internationalization API

I am experimenting with the new Internationalization API using Chrome Version 31.0.1623.0 canary. My goal is to: Convert Date Time between UTC and a specific time zone (America/New_York as an example). Determine if the conversion takes into account Dayl ...

Issues arise when trying to use the Jquery append() method in conjunction with Angular

We are currently utilizing jquery version 1.9.1 and angular version 1.2.13 for our project. Our wysiwyg editor is functioning well, as we are able to save HTML into the database and load it back using the jquery append function successfully. However, we ar ...

determine the color of the pixel at the top left corner of a jpg image

If we were given a specific URL, for instance, "//upload.wikimedia.org/wikipedia/en/a/a9/Example.jpg", how can we use javascript (specifically jQuery or Angular) to obtain the top left coordinates (or any (x,y) coordinates) of this image? Just to clarify, ...

Issue: Unable to find suitable routes for navigation. URL Segment: 'profile' or Encounter: Server could not load resource as response status is 401 (Unauthorized)

Currently, I am working on the MEANAUTH application and encountering an issue with accessing user profiles using angular jwt. When attempting to log in and access user profiles at https://localhost:3000/profile, I receive the following error message: Faile ...

Using Spring MVC and Thymeleaf to dynamically load new HTML pages on ajax calls

Hello there, I'm looking to dive into using thymeleaf for my web application. My goal is to create a simple website with HTML pages. Below is the URL of my landing page controller that returns the index.html page: @RequestMapping("/index") public Str ...

The error message "Potree-Core: THREE is undefined" indicates that the

I'm currently developing a web-based application that can be used offline by other users on their local machines. Within my NPM project, I am utilizing Potree-Core, which relies on THREE.js. However, the source code does not include an import for THR ...

What is the best way to retrieve the previous state of a file field in React?

Currently, I am working on implementing an on-change handler for an audio file in a component. The goal is to load the previous state of the file when the user changes it and records the new path. Specifically, when the user enters the component, the file ...

Ways to implement shader on a THREE.Object3D that has been loaded using OBJMTLLoader

After loading a model with THREE.OBJMTLLoader, I want to add a vertex and fragment shader to it. var loader = new THREE.OBJMTLLoader(); loader.addEventListener('load', function(event) { var mesh = event.content; scene.add(mesh); }); load ...

In Next.js, encountering an error when using canvas drawImage

I am attempting to upload a local image onto a canvas element, but I keep encountering an error: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(CSSImageValue or HTMLCanvasElement ...

Testing in Xcode unit is key

Although I am familiar with the concept of Unit Testing, I have never actually implemented it in my work. I grasp its benefits but struggle to determine the optimal scenarios and techniques for applying it. I am seeking guidance on when it is most advanta ...

Arrange divs adjacent to each other without any gaps in between

My HTML code includes elements from Twitter Bootstrap and AngularJS framework. <div class="item item-custom-first"> <select class="form-control" style="display:inline; float:right" ng-model="requestdata.units ...

Identifying the moment when attention shifts away from an element

Is it possible to detect when focus occurs outside an element without relying on global selectors like $(document), $(body), or $(window) for performance reasons? If achieving this without global selectors is not feasible, provide a provable reason expla ...

Continuously encountering the "Uncaught Error: Bootstrap dropdown requires Popper.js" message despite having already added popper.js to the code

Recently beginning my journey with Angular and Bootstrap, I decided to create a simple "hello world" app. I've included all the necessary libraries, but I encountered an error that has me stuck. Error: Bootstrap dropdown requires Popper.js I' ...