我有两个视图控制器,我试图将数据从一个传递到另一个。数据从 MKLocalSearch 闭包返回。但我似乎无法让我的委托方法运行。我希望有人能对此有所了解吗?我模拟了我正在尝试做的一个较小的版本。另外,我不使用故事板。我把所有东西都编码了。这是代码...
import UIKit
import MapKit
protocol SendDataDelegate {
func sendData(data: String)
}
class OneViewController: UIViewController {
var delegate: SendDataDelegate?
override func viewDidLoad() {
super.viewDidLoad()
doSearch() { coord in
if let coord = coord {
//When the execution gets here, coord does have
//the values to be sent to the nexr view controller.
self.delegate?.sendData(data: "\(coord)")
let twoViewController = TwoViewController()
self.present(twoViewController, animated: true)
}
}
}
func doSearch(completion: @escaping (CLLocationCoordinate2D?) -> Void) {
var coord: CLLocationCoordinate2D?
let request = MKLocalSearchRequest()
request.naturalLanguageQuery = "New York"
let search = MKLocalSearch(request: request)
search.start(completionHandler: {(response, error) in
if error != nil {
print("Error occured in search:\(error!.localizedDescription)")
} else if response!.mapItems.count == 0 {
print("No matches found")
} else {
print("Matches found")
coord = response?.mapItems[0].placemark.coordinate
}
completion(coord)
})
}
}
import UIKit
class TwoViewController: UIViewController, SendDataDelegate {
var myData: String = ""
var oneViewController = OneViewController()
override func viewDidLoad() {
super.viewDidLoad()
oneViewController.delegate = self
}
func sendData(data: String) {
myData = data
print ("myData: \(myData)")
}
}