iosswiftuiviewcontroller

Execute a function before viewDidLoad


This view is going to present a set of questions. These questions will be read from an API. I have 2 ways either to load them in the last view or load them in the current view but before the viewDidLoad method. I tried the viewWillAppear but didn't work well. How can I do that?

Edit:

This is the function that reads the data from the API:

func readData(id: String, userCompletionHandler: @escaping ([String], Error?) -> Void){
            let request = NSMutableURLRequest(url: NSURL(string: "http://adminsapi.somee.com/Api/Test/?id=\(id)")! as URL, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0)
            request.httpMethod = "GET"

            var questionArr = [String]()
            let session = URLSession.shared
            let dataTask = session.dataTask(with: request as URLRequest, completionHandler: {
                (data, response, error) in
                if response != nil {
                    //print("Response: \(response!)")
                }
                if let data = data {
                    do{
                        self.questionObject = try JSONDecoder().decode([Questions].self, from: data)
                        for question in self.questionObject{
                            questionArr.append(question.question)
                        }
                        userCompletionHandler(questionArr, nil)
                    } catch{
                        print("Error in retrieving data: \(error)")
                    }
                }
                else{
                    print("Error: \(String(describing: error))")
                }
                })
            dataTask.resume()
        }

and this is the where I navigate to the next View Controller:

func moveToNextVC(finalString: String){
        let VC1 = self.storyboard?.instantiateViewController(withIdentifier: "QuestionsTableViewController") as? QuestionsTableViewController
        if finalString.lowercased().contains("abdominal distention"){
            readData(id: "1", userCompletionHandler: { data, error in
                VC1?.questions = data
            })
            self.present(VC1!, animated: true, completion: nil)
        }
    }

The problem is when I print the questions array in "QuestionsTableViewController" it is always empty


Solution

  • In order from left to right

    loadView -> viewDidLoad -> viewWillAppear

    there is no much time enough to do this either in loadView , you need to load the api in the previous vc then show the needed 1 , or make the call inside viewDidLoad