Home > Blockchain >  Can't pass data between View Controller and Model
Can't pass data between View Controller and Model

Time:12-28

There is UIAlertController with text field in my View Controller. When user enter name of the city, this data must be transmitted to Model, when I get coordinates of this city. But I can't to pass name of the city from View Controller to Model

My 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)
    }

My Model:

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

CodePudding user response:

I think it is supposed to be var delegate: LocationGroup()

Also, I wouldn't be calling it delegate because registered delegate is a keyword in swift

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

  • Related