0

Right now I have been able to access the data I am trying to grab from JSON. Now I need to create a variable to hold the data because we don't want to store it in our database.

I have tried making the variable totalBalance store the value as optional but it gives me an error because I try to return it in the function and it comes back as nil and breaks the app. When I assign it a value of 0, zero is returned because the function doesn't run in order, but runs the return statement at the same time as the alamofire request, causing the variable to never be assigned the correct value. I want totalBalance to return the totalBalance from the function. Print statements show where the totalBalance value dies.

var totalBalance: Double = 0

func grabBalance() -> Double {
    var getBalance: Double = 0

    Alamofire.request("http://localhost:8000/accounts/balance/get", method: .post, parameters: parameters, encoding: JSONEncoding.default).responseJSON { response in
        print("Request: \(String(describing: response.request))")   // original url request
        print("Response: \(String(describing: response.response))") // http url response
        print("Result: \(response.result)")

        if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
            print("Data: \(utf8Text)") // original server data as UTF8 string
        }                      // response serialization result

        if let json = response.result.value {
            print("JSON: \(json)") // serialized json response
            let jsonValue = JSON(json)
            if let items = jsonValue["balanceResponse"]["accounts"].array {
                for item in items {
                    if let current = item["balances"]["current"].double{
                        print(current)
                        getBalance = getBalance + current
                    }
                    self.totalBalance = getBalance
                }
            }
        }
        print("This is where it shows the total balance: \(self.totalBalance)")
    }
    print("This is where it shows that it is 0: \(self.totalBalance)")
    return self.totalBalance
}
Ian Keller
  • 800
  • 5
  • 5

1 Answers1

0

When you make a request using Alamofire, you are using an Asynchronous request, which means your code following the request will be execute and will not wait for the request to finish.

In your specific case, you can return the totalBalance on you success callback

113408
  • 3,364
  • 6
  • 27
  • 54