Example of calling swift code from RN

This commit is contained in:
Artur Gurgul 2025-08-03 12:53:34 +02:00
parent 1a9884e0e9
commit 151ed6d78b
12 changed files with 86 additions and 6 deletions

30
App.tsx
View file

@ -1,12 +1,13 @@
import { NewAppScreen } from '@react-native/new-app-screen'
import { useEffect, useState } from 'react'
import { StatusBar, Text, StyleSheet, useColorScheme, ScrollView } from 'react-native'
import { StatusBar, Text, StyleSheet, useColorScheme, ScrollView, Button, Alert } from 'react-native'
import { NativeEventEmitter, NativeModules } from 'react-native'
const { Emitter } = NativeModules
const { Emitter, TestingServiceModule } = NativeModules
import { requireNativeComponent } from 'react-native'
import type { StyleProp, ViewStyle } from 'react-native'
type CustomButtonProps = {
style?: StyleProp<ViewStyle>
}
@ -15,9 +16,23 @@ const BaseButton = requireNativeComponent<CustomButtonProps>('BaseButton')
export default function App() {
const isDarkMode = useColorScheme() === 'dark'
const [message, setMessage] = useState(null)
const [message, setMessage] = useState<string|null>(null)
const [color, setColor] = useState("#FFF")
const onPress = async () => {
if (!TestingServiceModule?.greet) {
Alert.alert('Module not found', 'MyNativeModule is not linked or not exported.')
return
}
try {
const result = await TestingServiceModule.greet('John')
setMessage(result);
} catch (e) {
//Alert.alert('Error', String(e?.message ?? e))
}
}
useEffect(() => {
const emitter = new NativeEventEmitter(Emitter);
const subscription = emitter.addListener('onMessage', (event) => {
@ -28,6 +43,14 @@ export default function App() {
setColor("#00F")
}
}
TestingServiceModule.greet('John')
.then((message: string) => {
setMessage(message)
})
.catch((error: string) => {
console.error(error);
});
})
return () => {
@ -41,6 +64,7 @@ export default function App() {
<Text>{message ?? 'Waiting for message...'}</Text>
<CustomButton style={{ height: 200 }} />
<BaseButton style={{ height: 200 }} />
<Button title="Call Swift greet()" onPress={onPress} />
</ScrollView>
);
}