Randy Saeks
Randy Saeks

Reputation: 51

Adding a completion handler to Alamofire

I'm working on a small chunk of Swift code to work with pulling data via web-based APIs. Right now I am close, but think I'm missing the completion handler aspect when I print the data within the getUserInfo() expected data is there, but outside that function, the initialized default data appears. The function is called like this:

print("Provided Username is: \(workingData.user)")
getUserInfo()
print("Returned String Data is: \(workingData.responseDataString)")

and the actual function:

func getUserInfo() {
    Alamofire.request(workingjss.jssURL + devAPIMatchPath + workingData.user, method: .get)
        .authenticate(user: workingjss.jssUsername, password: workingjss.jssPassword).responseString { response in
            if (response.result.isSuccess) {
                print("In Function Data: \(response.result.value!)"
                workingData.responseDataString = response.result.value!
            }
    }
}

The output in running the code is:

Provided Username is: MYUSER
Returned String Data is: Nothing Here Yet 
In Function Data: {"Cleaned JSON Data here"}

Would a completion handler help the issue out? I'm pretty new to working with Alamofire so sorry if this is an easy one. Thanks!

Upvotes: 1

Views: 7618

Answers (1)

chengsam
chengsam

Reputation: 7405

Try using a completion handler:

func getUserInfo(completion: @escaping (String) -> Void) {
    Alamofire.request(workingjss.jssURL + devAPIMatchPath + workingData.user, method: .get)
        .authenticate(user: workingjss.jssUsername, password: workingjss.jssPassword).responseString { response in
            if (response.result.isSuccess) {
                print("In Function Data: \(response.result.value!)"
                completion(response.result.value!)
            }
    }
}

And call it like:

getUserInfo() { response in
    // Do your stuff here
    workingData.responseDataString = response
    print("Returned String Data is: \(workingData.responseDataString)")
}

Upvotes: 12

Related Questions