k.thomas
k.thomas

Reputation: 51

How to set default UITextField values through view did load

I am trying to load default values to textfields from JSON data saved to a struct. The function that gets the JSON data is running in viewdidload. I have the code under viewdidlod and it returns nil values. to test to code I ran in under IBAction and is worked fine. How do I get the code to run correctly in viewdidload?

override func viewDidLoad() {
    super.viewDidLoad()

    setUpPicker(textField: lenderName, pickerView: lenderNamePicker, PickerViewDelegate: self, PickerViewDataSource: self)
    setUpPicker(textField: mortgageTerm, pickerView: mortgageTermPicker, PickerViewDelegate: self, PickerViewDataSource: self)

    SelectionFunctions.MortgageTermSelection()

    getRates (completion: { [weak self] in
        self?.lenderName.reloadInputViews()
    })

    DispatchQueue.main.async {
        let setupLender = Data.currentRateData.first(where: {$0.financialInstitution == "CIBC Mortgages"})
        let setupRate = setupLender?.fiveYear
        self.mortgageRate.text = setupRate?.percentage
        print(setupRate)
        print(setupLender)
        print(Data.currentRateData.first?.financialInstitution)
    }

    lenderName.text = "CIBC Mortgages"
    mortgageAmount.text = "$300,000.00"
    orginalStartDate.text = ""
    mortgageTerm.text = "5 Year"
    //mortgageRate.text = "3.89%"
    OrginalDiscount.text = "1.25%"
    cashback.text = "$2,000"

    lenderName.addDoneButton()
    mortgageAmount.addDoneButton()

    orginalStartDate.addDoneButton()
    mortgageTerm.addDoneButton()
    mortgageRate.addDoneButton()
    orginalStartDate.addDoneButton()
    cashback.addDoneButton()
    OrginalDiscount.addDoneButton()

    func setupDelegate(textField: UITextField){
        textField.delegate = self
    }

    setupDelegate(textField: mortgageAmount)
    setupDelegate(textField: mortgageRate)
    setupDelegate(textField: OrginalDiscount)
    setupDelegate(textField: cashback)


    DatePicker()
}

Upvotes: 0

Views: 152

Answers (1)

rmaddy
rmaddy

Reputation: 318794

Simply move the use of DispatchQueue.main.async inside the completion block of the getRates call.

getRates (completion: { [weak self] in
    self?.lenderName.reloadInputViews()

    DispatchQueue.main.async {
        let setupLender = Data.currentRateData.first(where: {$0.financialInstitution == "CIBC Mortgages"})
        let setupRate = setupLender?.fiveYear
        self.mortgageRate.text = setupRate?.percentage
        print(setupRate)
        print(setupLender)
        print(Data.currentRateData.first?.financialInstitution)
    }
})

I'm assuming that the getRates call is what is loading the data being used inside the DispatchQueue.main.async block.

Upvotes: 1

Related Questions