无法在视图控制器和模型之间传递数据



在我的视图控制器中有一个带有文本字段的UIAlertController。当用户输入城市名称时,当我得到这个城市的坐标时,这些数据必须传输到Model。但我不能把城市的名字从视图控制器传给模型

我的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()
}
}

我认为应该是var delegate:LocationGroup((

此外,我不会称之为delegate,因为注册的delegate是swift 中的一个关键字

https://manasaprema04.medium.com/different-ways-to-pass-data-between-viewcontrollers-views-8b7095e9b1bf

最新更新