【问题标题】:Unable to call swift function from objective-c in react-native无法在 react-native 中从 Objective-c 调用 swift 函数
【发布时间】:2020-09-06 22:06:15
【问题描述】:

我对 Objective-c 和 swift 相当陌生,如果这听起来很愚蠢,请原谅我。基本上我要做的是*暴露**一个快速函数到both react-native(所以它可以在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

MyApp.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 中删除代码,则会收到错误“No visible @interface for...”但修复了 MyApp- 中的“重复接口错误” Bridging-Header.h。好像互相矛盾啊!?你应该如何从 Objective-c 调用一个 swift 函数,同时将相同的函数暴露给 JS?

【问题讨论】:

  • 桥接头用于在 swift 中调用 objc。为了在 objc 中调用 swift,xcode 会自动生成另一个标头。在项目构建设置中查找 SWIFT_OBJC_INTERFACE_HEADER_NAME 值
  • 你不应该在任何地方导入桥接头,也不应该在那里声明类。

标签: ios objective-c swift react-native


【解决方案1】:

我在一个项目中做类似的事情,我的设置是这样的:

Counter.m

#import "React/RCTBridgeModule.h"
#import "React/RCTViewManager.h"

@interface RCT_EXTERN_MODULE(Counter, NSObject)
RCT_EXTERN_METHOD(start)
RCT_EXTERN_METHOD(stop)
@end

Counter.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 非常有帮助。

【讨论】:

    猜你喜欢
    • 2020-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-18
    • 2014-07-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多