Mattk90 Mattk90 - 7 months ago 39
Swift Question

How to wait for a function to end on iOS/Swift, before starting the second one

I basically have to methods, which are being called in my viewDidLoad. The first one gets the user's search preferences and saves the preferences to variables at the top. After that I want to access and work with these variables in the second function. But now the variables are always nil when I want to access them in the second function.

How do I need to adjust my viewDidLoad, so the second function is only executed once and my data request has been performed successfully?

var searchLocation = String()
var searchLocationCoordinates = [String:Double]()
var searchRange = Int()


override func viewDidLoad() {
super.viewDidLoad()

// Gets the user's search preference
getTheSearchLocationAndRange()

// Loads the data from the database
loadDataFromDatabase()
}


I have read stuff so far with dispatch_asynch or completion handler. Maybe someone can post some code which I can use in my viewDidLoad and makes it work?

Answer

Okay I've found an solution. I basically called the function at the end of the first one.

So basically:

    var searchLocation = String()
    var searchLocationCoordinates = [String:Double]()
    var searchRange = Int()


    override func viewDidLoad() {
        super.viewDidLoad()

        // Gets the user's search preference
        getTheSearchLocationAndRange()
    }

    func getTheSearchLocationAndRange() {
    // Code for getTheSearchLocationAndRange()

    loadDataFromDatabase()
    }

    func loadDataFromDatabase(){
    // Code for loadDataFromDatabase()
    }
Comments