1

My current function is as follows:

public func getToken() -> String {
    Alamofire.request("url", method: .post, encoding: JSONEncoding.default)
        .responseData { response in
            if let data = response.data {
                let xml = SWXMLHash.parse(data)
                let token  = ((xml["authResponse"] ["authToken"].element?.text))!
            }
        }

    return token // Test is undefined down here
}

I am trying to get this function to return the token string but the variable token is undefined.

Donut
  • 110,061
  • 20
  • 134
  • 146
Martheli
  • 931
  • 1
  • 16
  • 35

1 Answers1

0

There are multiple problems with this code. The first and most obvious is that token is only in scope within the inner closure, so it's not defined where your return statement is located. However, the second problem is that your Alamofire request will be made asynchronously, but the signature of your getToken method assumes that the resulting value will be provided synchronously.

I'd suggest changing the signature of your method to accept another closure as a parameter as a "callback" method. Something along these lines:

public func getToken(callback: ((String?) -> Void)) -> String {
    Alamofire.request("url", method: .post, encoding: JSONEncoding.default)
        .responseData { response in
            if let data = response.data {
                let xml = SWXMLHash.parse(data)
                let token  = ((xml["authResponse"] ["authToken"].element?.text))!
                callback(token)
            } else {
                callback(nil)
            }
        }
}

Then, you could call it like this:

getToken(callback: { token in
    if let token = token {
        print("Got the token: \(token)")
    } else {
        print("Didn't get the token: ¯\_(ツ)_/¯")
    }
})

You'd probably want to add some more robust error handling, and maybe a way to disambiguate between an error and an actual nil value being returned (if that's even possible). I'd also suggest getting rid of the forced unwrapping in your getToken method. Hopefully this solves your original problem though.

Donut
  • 110,061
  • 20
  • 134
  • 146