SwiftyJD SwiftyJD - 6 months ago 20
Swift Question

In Swift, how to write a function that triggers another function once it's complete?

I currently have a function that returns JSON data, in that JSON data is an access token (function uses both AlamoFire & SwiftyJSON):

func getAccessToken (username: String, password: String) {

//code//

Alamofire.request(.POST, "\(baseURL)/oauth2/token", parameters: parameters, encoding: .JSON, headers: headers)

.responseJSON { response in
if((response.result.value) != nil) {

let swiftyJsonVar = JSON(response.result.value!)

self.accessToken = swiftyJsonVar["access_token"].stringValue

}
}
}


As soon as I get the access token I want another function to be triggered using the access token that was just gotten:

func createNewMember (username: String, password: String, accessToken: String) {
//code//
}


I was thinking of having a closure on the
getAccessToken
function that returns the access token and triggers the
createNewMember
function but am not entirely sure how to set it up. Any help is appreciated!

Rob Rob
Answer

I would suggest a completionHandler pattern, a closure that you will call when the getAccessToken call is done, which can return either the token or the error:

func getAccessToken (username: String, password: String, completionHandler: (String?, ErrorType?) -> ()) {

    //code//

    Alamofire.request(.POST, "\(baseURL)/oauth2/token", parameters: parameters, encoding: .JSON, headers: headers)
        .responseJSON { response in
            guard let value = response.result.value else {
                completionHandler(nil, response.result.error)
                return
            }

            let swiftyJsonVar = JSON(value)
            completionHandler(swiftyJsonVar["access_token"].string, nil)
    }
}

You'd then call it using the completion handler closure:

getAccessToken(username, password: password) { token, error in
    guard let accessToken = token where error == nil else {
        // handle error here

        print(error)
        return
    }

    self.createNewMember(username, password: password, accessToken: accessToken)
}