UYAR.C
UYAR.C

Reputation: 151

How can call a ViewController class on native ıos when react-native app view load?

I want create an react-native app. In this app, ı want to use my swift code. When react-native app view loaded an ios device ı want to call my swift code like native ıos app.

Thanks

Upvotes: 1

Views: 735

Answers (1)

Maciej Gad
Maciej Gad

Reputation: 1731

I'm not a react-native specialist, but I think you should create a class in Swift, export it in Objective-C (make it accessible from JavaScript) and then use in your JavaScript code. I will assume that you already have a project in Xcode. There are a few steps that you need to do:

  1. Add a swift file to your project: File → New → File… (or CMD+N) select Swift type and provide a name

  2. You will be asked if you want to create an Objective-C Bridging Header and select "Create Bridging Header"

  3. The file your-project-name-Bridging-Header.h will be created (where your-project-name is a name of your project), this is a glue between objective-c and swift, and we will use it to export our code to JavaScript

  4. To show you some example I will use this code for swift file:

import Foundation

@objc(Counter) //1
class Counter: NSObject { //2
  private var count = 0
  @objc //3
  func increment() {
    count += 1
    print("count is \(count)")
  }
}

Make sure that you notice some important parts (that differ from typical swift code): marks 1 and 3 - you have to add @objc declaration for class and function, (2) the class should inherit from NSObject

  1. In your-project-name-Bridging-Header.h you need to use this code to be able to use your swift code in JavaScript:
#import "React/RCTBridgeModule.h"

@interface RCT_EXTERN_MODULE(Counter, NSObject)
RCT_EXTERN_METHOD(increment)
@end
  1. Add this code to your App.js:
// App.js
import { NativeModules } from 'react-native'

NativeModules.Counter.increment()

All those examples are taken from this article: Swift in React Native - The Ultimate Guide Part 1: Modules which I highly recommend reading, because it contains a lot more details in the topic.

Upvotes: 3

Related Questions