Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - Call segue inside of a closure

I am trying to call a segue inside of a closure and I can't seem to make it work. The problem is that I don't know how to make the "performSegueWithIdentifier" call since I cannot use the keyword "self" here.

This is being done outside of UIViewController, so I don't know how to call a "performSegueWithIdentifier" without using the keyword "self".

So I would need to create the object where the method is called, but how and which object? Is it the view controller? On the storyboard? or where is it?

func signUp (username: String, password: String) {
    Alamofire.request(.POST, "https://test.xyz.de/api/v1/public/user", parameters:["username" : username, "password": password], encoding: .JSON)
        .responseJSON({ (_, _, JSON, error) -> Void in
            println("Response: \(JSON)")
            if error == nil {
                self.performSegueWithIdentifier("segueToNextScreen", sender: self) // Problem!!
            } else {
                println(error)
            }
        })
}

Thanks in advance and let me know if you need further explanation.

Cheers, Tiago

like image 665
iagomr Avatar asked Sep 29 '22 17:09

iagomr


2 Answers

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

Alamofire.request(.POST, "https://test.xyz.de/api/v1/public/user", parameters:["username" : username, "password": password], encoding: .JSON)
    .responseJSON({ (_, _, JSON, error) -> Void in
        println("Response: \(JSON)")

        if error == nil {

            dispatch_async(dispatch_get_main_queue()){
                self.performSegueWithIdentifier("segueToNextScreen", sender:self)
                }
        } 
        else {

            println(error)
        }
    })
}

Encapsulating "performSegueWithIndentifier" inside "dispatch_async" worked for me.

like image 106
Charles B Avatar answered Oct 02 '22 23:10

Charles B


You could write a function which you will call inside the block which will perform the seuge. That way you can use the self keyword:

func performSegue(identifier:String){
  self.performSegueWithIdentifier(identifier, sender: self)
}

func signUp (username: String, password: String) {
    Alamofire.request(.POST, "https://test.xyz.de/api/v1/public/user", parameters:["username" : username, "password": password], encoding: .JSON)
        .responseJSON({ (_, _, JSON, error) -> Void in
            println("Response: \(JSON)")
            if error == nil {
                self.performSegue("segueToNextScreen") // Problem!!
            } else {
                println(error)
            }
        })
}
like image 27
Christian Avatar answered Oct 03 '22 00:10

Christian