使用Swift Singleton自定义类的React-native桥接

时间:2019-04-02 10:36:50

标签: ios objective-c swift react-native

今天,我尝试使用自定义的Swift类在Javascript代码中实现Singleton模式。我已经创建了本机模块,但今天却遇到此错误:“ 致命错误:对类使用未实现的初始化程序'init()'

我想这是因为Singleton模式,但我无法理解我的错误...

这是我的代码:

AnalyticsTracker.swift

import Foundation
import Tracker


@objc(AnalyticsTracker)
class AnalyticsTracker: NSObject {


  static let shared = AnalyticsTracker(tracker: ATInternet.sharedInstance.defaultTracker)

  // MARK: -

  let tracker: Tracker

  // Initialization

  private init(tracker: Tracker) {
    self.tracker = tracker
  }

  @objc
  func viewScreen(screen: String) {
    self.tracker.screens.add(screen).sendView()
  }

  @objc
  func sendTouch(clickName: String, chapter1: String, chapter2: String, chapter3: String, level2: Int) {
    let gesture = self.tracker.gestures.add(clickName, chapter1: chapter1, chapter2: chapter2, chapter3:chapter3)
    gesture.level2 = level2
    gesture.sendTouch()
  }
}

还有将类导出到我的本地应用程序的模块:

AnalyticsTracker.m

#import <Foundation/Foundation.h>
#import <React/RCTBridgeModule.h>

@interface RCT_EXTERN_MODULE(AnalyticsTracker, NSObject)

RCT_EXTERN_METHOD(
                  sendTouch:
                  (NSString*)clickName
                  (NSString*)chapter1
                  (NSString*)chapter2
                  (NSString*)chapter3
                  (int)level2
)

@end

当我删除导出模块时,错误消失了。我真的不明白错误的含义...

如果有人有想法,将不胜感激:)

2 个答案:

答案 0 :(得分:2)

问题出在React Native的桥接机制中。 AFAIK它不支持自定义初始化。作为解决方法,您可以创建一个在其导出方法中使用AnalyticsTracker.shared的帮助程序类:

// RNAnalyticsTracker.swift

import Foundation

@objc(RNAnalyticsTracker)
class RNAnalyticsTracker: NSObject {

  @objc
  func viewScreen(screen: String) {
    AnalyticsTracker.shared.viewScreen(screen: screen)
  }

  @objc
  func sendTouch(clickName: String, chapter1: String, chapter2: String, chapter3: String, level2: Int) {
    AnalyticsTracker.shared.sendTouch(clickName: clickName, chapter1: chapter1, chapter2: chapter2, chapter3: chapter3, level2: level2)
  }
}

来源参考:https://gist.github.com/harveyconnor/7b0e778effaae302f512485c18881569

答案 1 :(得分:0)

您将继承NSObject,因此必须提供公共的初始化构造函数,该构造函数将初始化您的tracker属性。