Rayson Yong
Rayson Yong

Reputation: 11

Can my react-native application use xcode swift libraries? and How?

I'm currently quite new to react-native and xcode. So basically, I made a program on xcode using swift and importing a library, but now I need to use this code in my react native application. I don't know if it is possible and how to go about doing it.

Upvotes: 1

Views: 653

Answers (1)

MK Coder
MK Coder

Reputation: 106

Unfortunately it really depends on how you want to use your swift code, because React Native provides different methods for different circumstances, but I will try to give you an example of an basic "Event Bridge". First of all every React Native Application automatically generates an iOS and Android project. Navigate to the iOS folder and open the Xcode workspace. Afterwards just drag your swift source file into the project (like in every other native application). As React Native uses an Objective-C Bridge we cannot directly use the Swift code so we need to bridge Swift -> Objc -> Javascript.

Lets first dive into your Swift class:

You need to be able to communicate with objc and export the methods to the react native runtime, here is an example of the swift file

// CustomObject.swift
import Foundation

@objc(CustomObject)
class CustomObject: NSObject {

@objc static var isSelected = false // our state

  @objc
  func selectObject() {
    CustomObject.isSelected.toggle()
    print(CustomObject.isSelected ? "selected" : "not selected")
  }

  @objc
  func getState(_ callback: RCTResponseSenderBlock) {
    callback([NSNull(), CustomObject.isSelected]) // this will return into a  
    // javascript callback to retrieve the current state
  }

  // this is needed to make sure that this will run on the main thread 
  @objc
  static func requiresMainQueueSetup() -> Bool {
    return true
  }
}

Now we need to call these methods from Objc and expose it to JavaScript.

// CustomObject.m

#import "React/RCTBridgeModule.h"

@interface RCT_EXTERN_MODULE(CustomObject, NSObject)
RCT_EXTERN_METHOD(selectObject)
RCT_EXTERN_METHOD(getState: (RCTResponseSenderBlock)callback)
@end

This is all you have to do.

Now you can navigate back to your JavaScript Application and import NativeModules.

import React, {useState} from 'react';
import {View, NativeModules, Button, Text} from 'react-native';

const TestComponent = () => {
const [selected, setSelected] = useState(false);
      
const triggerSelection = () => {
  NativeModules.CustomObject.selectObject()
  NativeModules.CustomObject.getState( (err, isSelected) => { // Edited
   setSelected(isSelected);
  });
}

return (
     <View>
       <Button title="Button" onPress={triggerSelection} />
       <Text>{selected}</Text>
     </View>
 );

}

To pass more complex structures from native to javascript, just take a look at this documentation, it is actually not that bad.

React Native - Native Modules

Upvotes: 1

Related Questions