Search code examples
swiftdelegatesdelegation

My delegate function is not being called in Swift


I have a main view titled NoteTakerViewController. I have a weatherGetterController class with a protocol that returns 5 days of weather with a protocol function called getMyWeather. However the protocol function is not being called that returns the weather data to NoteTakerViewController. I am certain I have everything set up correctly with the delegates but perhaps I do not.

This is really not a duplicate of Swift Delegate Not Being Called as the solution on that page did not work.

Any help you could provide would be great.

Here's the relevant code snippets:

My weatherGetterController class:

protocol WeatherGetterControllerDelegate {
    func getMyWeather(weather: [FiveDayForecast])
}

class WeatherGetterController: UIViewController, CLLocationManagerDelegate {

var weatherGetterDelegate: WeatherGetterControllerDelegate?

And in the WeatherGetterController "getWeather" function call. The line

self.weatherGetterDelegate?.getMyWeather(weather: myForecast)

is not being called.

func getWeather() {
       ...
       getNetWeather { (fetchedInfo) in

            if let fetchedInfo2 = fetchedInfo {
                //self.updateUI(mainWeather: fetchedInfo2)
                //need to call delegate here
                let myForecast = self.figureFive(weather: fetchedInfo2)
                //return the forecast
                print(myForecast)
                self.weatherGetterDelegate?.getMyWeather(weather: myForecast)

            }

        }

Finally the function implementation in NoteTakerViewController:


class NoteTakerViewController: UIViewController, ..., UITextFieldDelegate, WeatherGetterControllerDelegate

    func getMyWeather(weather: [FiveDayForecast]) {

        print("get my weather")
        print(weather)

    }

Through debugging I can see that "weatherGetterDelegate" is set to nil and I don't know why.

Thanks


Solution

  • First you need to make WeatherGetterController a property in NoteTakerViewController or a local variable where you call it but I will use the first option.

    class NoteTakerViewController: UIViewController, ..., WeatherGetterControllerDelegate {
        var weatherGetterController: WeatherGetterController?
    
        //...
    
        func viewDidLoad() {
             //....
             weatherGetterController = WeatherGetterController()
             weatherGetterController?.delegate = self
        }
    
       //And then in some other part of your code you do
       func someFunc() {
           self.weatherGetterController?.getWeather()
    

    I am curious why WeatherGetterController is define to be a viewcontroller, is that really correct?

    class WeatherGetterController: UIViewController, CLLocationManagerDelegate {
           
    

    Personally I would remove that part

    class WeatherGetterController: CLLocationManagerDelegate {