在本地响应中,我使用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)
}
}