I'm trying to set up a native iOS module for React Native with Swift.
我正在尝试使用Swift为React Native设置本机iOS模块。
Here's my Swift file:
这是我的Swift文件:
// SwiftManager.swift
import Foundation
@objc(SwitchManager)
class SwitchManager: NSObject {
@objc func addEvent(_ name: String) -> Void {
NSLog("It works!")
}
}
And here is my implementation file:
这是我的实现文件:
// SwiftManager.m
#import <React/RCTBridgeModule.h>
@interface RCT_EXTERN_MODULE(SwitchManager, NSObject)
RCT_EXTERN_METHOD(addEvent:(NSString *)name)
@end
Then, I try to use it in my React Native code like so:
然后,我尝试在我的React Native代码中使用它,如下所示:
// index.ios.js
import React, { Component } from 'react';
import { NativeModules } from 'react-native';
const SwitchManager = NativeModules.SwitchManager;
SwitchManager.addEvent('Birthday Party');
// ...
But SwitchManager
ends up being undefined. In another project I put together, I have successfully created a native module and I can't recall doing anything different. Do you have any ideas on why RN wouldn't pick up this native module?
但SwitchManager最终未定义。在我组建的另一个项目中,我已成功创建了一个本机模块,我不记得做了什么不同的事情。你有什么想法为什么RN不会拿起这个原生模块?
1 个解决方案
#1
1
I reverted all changes to a clean version of my repo and created the files from scratch again in Xcode. React Native is able to pick up the native module now. I think the problem could have been related to renaming things around and Xcode not keeping references properly, although I can't say for sure because I had several changes in my working tree.
我将所有更改还原到我的repo的干净版本,并在Xcode中再次从头开始创建文件。 React Native现在能够获取本机模块。我认为这个问题可能与重命名事件和Xcode没有正确保存引用有关,虽然我不能肯定地说,因为我的工作树中有几处更改。
#1
1
I reverted all changes to a clean version of my repo and created the files from scratch again in Xcode. React Native is able to pick up the native module now. I think the problem could have been related to renaming things around and Xcode not keeping references properly, although I can't say for sure because I had several changes in my working tree.
我将所有更改还原到我的repo的干净版本,并在Xcode中再次从头开始创建文件。 React Native现在能够获取本机模块。我认为这个问题可能与重命名事件和Xcode没有正确保存引用有关,虽然我不能肯定地说,因为我的工作树中有几处更改。