无法在 react-native 中从 objective-c 调用 swift 函数



我对objective-c和swift相当陌生,所以如果这听起来很愚蠢,请原谅我。基本上,我正在尝试做的是*公开**一个快速函数,以同时在反应本机(因此它可以在JS中使用(和在objective-c中使用。我遇到的问题是这个可怕的"类的重复接口定义..."。我已经研究并尝试了一切似乎,但无法摆脱这个错误。我开始怀疑是否有可能做到这一点。这看起来很简单,但我就是想不通!

这是我的代码:

AppDelegate.m

#import "MyApp-Swift.h"
#import "MyApp-Bridging-Header.h"

MyApp-Swift.h

#import "React/RCTEventEmitter.h"
@interface Counter : RCTEventEmitter
- (void)start;
- (void)stop;
@end

我的应用.swift

import Foundation
import UIKit
@objc(Counter)
class Counter: RCTEventEmitter {
@objc func start(){
}
@objc func end(){
}
}

MyApp-Bridging-Header.h

#import <Foundation/Foundation.h>
#import "React/RCTBridgeModule.h"
#import "React/RCTEventEmitter.h"
@interface RCT_EXTERN_MODULE(Counter, RCTEventEmitter)
RCT_EXTERN_METHOD(start);
RCT_EXTERN_METHOD(end);
@end

在 AppDelegate.m didFinishLaunchingWithOptions(( 函数中

Counter* CounterInstance = [[Counter alloc] init];
[CounterInstance start];

如果我从MyApp-Swift.h中删除代码,则会收到错误"没有可见@interface..."BUT 修复了MyApp-Bridging-Header.h中的"重复接口错误"。好像是自相矛盾的!?你应该如何从 objective-c 调用一个 swift 函数,同时将相同的函数公开给 JS?

我正在一个项目中做类似的事情,我的设置如下所示:

计数器

#import "React/RCTBridgeModule.h"
#import "React/RCTViewManager.h"
@interface RCT_EXTERN_MODULE(Counter, NSObject)
RCT_EXTERN_METHOD(start)
RCT_EXTERN_METHOD(stop)
@end

计数器.swift

import React
@objc(Counter)
class Counter: RCTEventEmitter {
@objc func start() { /* ... */ }
@objc func stop() { /* ... */ }
}

在呼叫站点:

#import "YOURAPP-Swift.h" // the compiler creates this for you. don't edit!
-(void) foo {
Counter* cnt = [Counter new];
[cnt start];
}

(未使用或修改其他文件。特别是,这里不需要桥接标头(

当我开始这样做时,我发现 https://teabreak.e-spres-oh.com/swift-in-react-native-the-ultimate-guide-part-1-modules-9bb8d054db03 非常有帮助。

最新更新