如何访问相邻 Swift class 方法中的回调函数

How to access callback function in adjacent Swift class method

我正在构建一个提示用户输入联系人的应用程序。我是 Swift 的新手,但取得了不错的进步。

我正在从父调用站点调用此 open 函数,并希望从 contactPicker 函数接收返回的响应值。我有点不熟悉 contactPicker 调用的隐含性质,并期望必须直接从 presentContactPicker 函数中调用它,但文档似乎表明这种方法更可取。

就目前而言,此实现正确提示联系人选择器 UI,并将所选联系人打印到控制台。但实际上我需要帮助将联系人传递给回调函数。

我遇到的问题是我无法从 contactPicker 内部访问回调函数。我有一种直觉,也许我可以在 open 函数中使用 self.callback = 回调之类的技术将回调附加到父 class,然后在 [=] 中调用 self.callback() 14=] 本身,但没有用。

import Foundation
import UIKit
import ContactsUI

@objc(ContactsPicker)
class ContactsPicker : NSObject, CNContactPickerDelegate {
  
  @objc static func requiresMainQueueSetup() -> Bool {
    return false
  }
  
  @objc func open(_ options: NSDictionary, callback: RCTResponseSenderBlock) -> Void {
    DispatchQueue.main.async {
      self._presentContactPicker(options: options)
    }
  }
  
  func _presentContactPicker(options: NSDictionary) -> Void {
      let contactPickerVC = CNContactPickerViewController()
      contactPickerVC.delegate = self
      let controller = RCTPresentedViewController()
      controller?.present(contactPickerVC, animated: true)
  }
  
  func contactPicker(_ picker: CNContactPickerViewController, didSelect contacts: [CNContact]) {
    print("+++++++++++++++++++++++++++")
    print(contacts)
    print("+++++++++++++++++++++++++++")

    ### But how can I access the callback from the exposed open method?
  }
}

maybe I could attach the callback to the parent class with a technique like self.callback = callback in the open function and then call self.callback() in the contactPicker itself

这是正确的想法。您可以像这样声明一个 属性 来存储回调:

private var callback: RCTResponseSenderBlock?

@objc func open(_ options: NSDictionary, callback: @escaping RCTResponseSenderBlock) -> Void {
    self.callback = callback
    DispatchQueue.main.async {
        self._presentContactPicker(options: options)
    }
}

请注意,由于回调“”进入class,您应该将参数标记为@escaping

func contactPicker(_ picker: CNContactPickerViewController, didSelect contacts: [CNContact]) {
    callback(someParameters)
}