Search code examples
iosswiftglobal-variablesnsjsonserialization

global variable not contain value on viewdidload in swift


variable containing data(1) while printing under jsonserialization method but in viewdidload it's showing nil value(0)

    var bank = Int()

    func getProfile() {
    .
    .
    .
    .
    let json = try JSONSerialization.jsonObject(with: data) as! [String: Any]
    print("json \(json)")

let status = json["Success"] as! Bool

if status {
//send profile update status 1
//After Alert Success
    DispatchQueue.main.async {
        if let banks = (json["bank"] as? NSString)?.intValue {


            print("banks\(banks)")
            self.bank = Int(banks)
            print("self.bank\(self.bank)")
        }
}



} else {


}
}

variable called under viewdidload showing 0(nil) value

    override func viewDidLoad() {
    getProfile()
    print("bank \(bank)")
    super.viewDidLoad()

    // Do any additional setup after loading the view.
}

output: bank 0


Solution

  • The main issue the variable isn't set because the webservice is called in another thread and the variable is printed before it's even loaded by the web service.

    Try to call it again in some button and you will see your result will print perfectly