【发布时间】:2022-01-23 05:08:02
【问题描述】:
在我的视图控制器中有带有文本字段的 UIAlertController。当用户输入城市名称时,这个数据必须传输给模型,当我得到这个城市的坐标时。但我不能将城市名称从视图控制器传递给模型
我的 UIAlertController:
class MainScrenenViewController: UIViewController {
var delegate: ILocationGroup?
@objc func locationButtonTap() {
let alert = UIAlertController(title: "Add city", message: nil, preferredStyle: .alert)
let addButton = UIAlertAction(title: "Add", style: .default) { action in
self.delegate?.addLocation(alert.textFields?.first?.text ?? "No City")
}
alert.addAction(addButton)
let cancelButton = UIAlertAction(title: "Cancel", style: .default, handler: nil)
alert.addAction(cancelButton)
alert.addTextField { textField in
textField.placeholder = "Your City"
}
present(alert, animated: true, completion: nil)
}
我的模特:
protocol ILocationGroup {
func addLocation(_ name: String)
}
class LocationGroup: ILocationGroup {
var mainScreenViewController: MainScrenenViewController?
func addLocation(_ name: String) {
mainScreenViewController?.delegate = self
let url = "https://geocode-maps.yandex.ru/1.x/?apikey=fd93783b-fe25-4428-8c3b-38b155941c8c&format=json&geocode=\(name)"
guard let url = URL(string: url) else { return }
let task = URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data, error == nil else { return }
do {
let result = try JSONDecoder().decode(LocationData.self, from: data)
print(result.response.geoObjectCollection.metaDataProperty.geocoderResponseMetaData.boundedBy.envelope.lowerCorner)
}
catch {
print("failed to convert \(error)")
}
}
task.resume()
}
}
【问题讨论】:
-
您必须在某处设置对
mainScreenViewController的引用。目前还不清楚这两个类是如何相关的。 -
你还需要在VC中设置委托。目前尚不清楚这是否在显示之前被注入到 VC 中。最后,您将 json 解码为 dataTask 完成块中的局部变量,但随后不对其执行任何操作(除了打印它),因此即使您确实设法将城市数据放入 URLSession,结果位置值也会丢失当关闭完成时。
标签: swift xcode uialertcontroller