Amir_P Amir_P - 4 months ago 22
Swift Question

Use interface to get response from another class

I'm making my request with Alamofire lib and I have a class for requests like Login,Register,... so I need an interface to notice when Alamofire receives responses. How can I do that in swift?

this is part of my Trans.swift

class Trans{
func getToken(username: String , password: String){
Alamofire.request(.GET, "http://www.shafadoc.ir/api/DocApp/Token?value=" + username + ":" + password ,parameters:nil)
.responseJSON{ response in
if let json = response.result.value{
}
}
}
}


and my LoginViewController:

if !login_password.text!.isEmpty || !login_username.text!.isEmpty
{
var trans : Trans = Trans
trans.getToken(login_username.text!, password: login_password.text!)
}

Answer

The block passed to .responseJSON method is where you are notified when the request completes. You can pass a callback block in trans.getToken and call the block inside .responseJSON. Like this:

func getToken(username: String , password: String, completion: Void -> Void){
    Alamofire.request(.GET, "http://www.shafadoc.ir/api/DocApp/Token?value=" + username + ":" + password ,parameters:nil)
        .responseJSON{ response in
            if let json = response.result.value{
            }
            //... do anything you want with the result, and finally:
            completion()    // <-- call the block
    }
}

In your view controller:

if !login_password.text!.isEmpty || !login_username.text!.isEmpty
{
    var trans : Trans = Trans
    trans.getToken(login_username.text!, password: login_password.text!) {
        //... do your UI stuff
    }
}