在 react native 中,我使用 NativeModules 和 RCTResponseSenderBlock 来创建回调。因为回调特定于我在桥中声明的函数,所以我无法从提供所需反馈的扩展中访问它。这是基于 Mapbox Navigation iOS SDK 的示例代码构建的。
我尝试了各种方法来通过扩展类访问回调属性。
@objc(TbtNavigation)
class TbtNavigation: NSObject {
@objc
func takeMeToWH(_ callback: RCTResponseSenderBlock) {
let origin = Waypoint(coordinate: CLLocationCoordinate2D(latitude: 38.9131752, longitude: -77.0324047), name: "Mapbox")
let destination = Waypoint(coordinate: CLLocationCoordinate2D(latitude: 38.8977, longitude: -77.0365), name: "White House")
let options = NavigationRouteOptions(waypoints: [origin, destination])
Directions.shared.calculate(options) { (waypoints, routes, error) in
guard let route = routes?.first else { return }
let navigationViewController = NavigationViewController(for: route)
navigationViewController.delegate = self
let appDelegate = UIApplication.shared.delegate
appDelegate!.window!!.rootViewController!.present(navigationViewController, animated: true, completion: nil)
}
callback(["CALLBACK WORKS HERE"])
}
}
extension TbtNavigation: NavigationViewControllerDelegate {
// Show an alert when arriving at the waypoint and wait until the user to start next leg.
func navigationViewControllerDidDismiss(_ navigationViewController: NavigationViewController, byCanceling canceled: Bool) {
print("cancelled")
callback(["I NEED THE CALLBACK TO WORK HERE"])
let appDelegate = UIApplication.shared.delegate
appDelegate!.window!!.rootViewController!.dismiss(animated: true, completion: nil)
}
}
navigationViewController 中的回调是“未解析的标识符”
编辑:解决方案是在类的范围内声明回调变量。
@objc(TbtNavigation)
class TbtNavigation: NSObject {
var callback: RCTResponseSenderBlock?
@objc
func takeMeToWH(_ callback: @escaping RCTResponseSenderBlock) {
let origin = Waypoint(coordinate: CLLocationCoordinate2D(latitude: 38.9131752, longitude: -77.0324047), name: "Mapbox")
let destination = Waypoint(coordinate: CLLocationCoordinate2D(latitude: 38.912605, longitude: -77.035402), name: "White House")
let options = NavigationRouteOptions(waypoints: [origin, destination])
Directions.shared.calculate(options) { (waypoints, routes, error) in
guard let route = routes?.first else { return }
let navigationViewController = NavigationViewController(for: route)
navigationViewController.delegate = self
let appDelegate = UIApplication.shared.delegate
appDelegate!.window!!.rootViewController!.present(navigationViewController, animated: true, completion: nil)
}
self.callback = callback
}
}
extension TbtNavigation: NavigationViewControllerDelegate {
// Show an alert when arriving at the waypoint and wait until the user to start next leg.
func navigationViewControllerDidDismiss(_ navigationViewController: NavigationViewController, byCanceling canceled: Bool) {
self.callback?([canceled])
let appDelegate = UIApplication.shared.delegate
appDelegate!.window!!.rootViewController!.dismiss(animated: true, completion: nil)
}
}