简体   繁体   English

我可以在不使用 Objective-C(纯 Swift)的情况下向 React Native 公开 Swift 函数吗?

[英]Can I expose a Swift function to React Native without using Objective-C (pure swift)?

I wonder if I can expose my func navigateToLoginWidget to React Native.我想知道是否可以将我的func navigateToLoginWidget公开给 React Native。 So that it can be triggered from RN.这样它就可以从RN触发。

I have managed to change the Objective-C template that comes with React Native to Swift like so:我设法将 React Native 附带的 Objective-C 模板更改为 Swift,如下所示:

 import Foundation import IBMCloudAppID import BMSCore import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var bridge: RCTBridge! func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // initializing App ID SDK let region = AppID.REGION_SOMEWHERE let backendGUID = "MY_TENANT_ID_FROM_IBM" AppID.sharedInstance.initialize(tenantId: backendGUID, region: region) // Initializing React Native front-end with Swift instead of Obj-c template let jsCodeLocation: URL jsCodeLocation = RCTBundleURLProvider.sharedSettings().jsBundleURL(forBundleRoot: "index.js", fallbackResource:nil) let rootView = RCTRootView(bundleURL: jsCodeLocation, moduleName: "MY_PROJECT_NAME", initialProperties: nil, launchOptions: launchOptions) let rootViewController = UIViewController() rootViewController.view = rootView self.window = UIWindow(frame: UIScreen.main.bounds) self.window?.rootViewController = rootViewController self.window?.makeKeyAndVisible() return true } func application(_ application: UIApplication, open url: URL, options :[UIApplication.OpenURLOptionsKey : Any]) -> Bool { return AppID.sharedInstance.application(application, open: url, options: options) } func navigateToLoginWidget(_ sender : Any) { print("clicked") AppID.sharedInstance.loginWidget?.launch(delegate: SigninDelegate) } }

I would normally have this function in another module called SigninDelegate.swift, but I have included it in the same class for explanatory purposes.我通常会在另一个名为 SigninDelegate.swift 的模块中使用此函数,但出于解释目的,我已将其包含在同一类中。

According to the official documentation :根据官方文档

Swift doesn't have support for macros so exposing it to React Native requires a bit more setup but works relatively the same. Swift 不支持宏,因此将其暴露给 React Native 需要更多的设置,但工作方式相对相同。

So yes, it is possible, but some setup is needed.所以是的,这是可能的,但需要一些设置。 Check the docs in the link above for the steps you need to follow to set it up.检查上面链接中的文档,了解设置它所需的步骤。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM