Search code examples
iosswiftseguesigabrt

Xcode, swift: SIGABRT error on performsegue


I am new to swift and I just started working on this project. It is a login app for ios. Here is the code for the "Log In" button. "Parola" means "password" by the way.

@IBAction func loginButton(_ sender: Any) {
    let Email = emailText.text;
    let Parola = parolaText.text;

    if((Email?.isEmpty)! || (Parola?.isEmpty)!){
        print("Empty field!")
    } else {

    let myUrl = NSURL(string: "http://my.url/webservice.php");
    let request = NSMutableURLRequest(url:myUrl! as URL);
    request.httpMethod = "POST";

    let postString = "email=\(String(describing: Email!))&password=\(String(describing: Parola!))";
    request.httpBody = postString.data(using: String.Encoding.utf8);


    let task = URLSession.shared.dataTask(with: request as URLRequest){
        data, response, error in

        if error != nil {
            print("error=\(String(describing: error))")
            return
        }

        var err: NSError?
        do {
            let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary

            if let parseJSON = json {
                var resultValue:String = parseJSON["status"] as! String;
                print("result: \(resultValue)");

                if(resultValue == "Success"){
                    self.performSegue(withIdentifier: "LogPers", sender: nil)
                }
            }

        } catch let error as NSError {
            err = error
        }
    }

    task.resume()

}
} 

It connects to a external database by using a web service to verify the inputed user information. All of that works fine.

My problem is the SIGABRT error I get when the app tries to execute the segue. I tried searching this problem online and all of the sources said that this error is caused by buggy outlets and connections, but all of my outlets are ok.

If I take the segue outside of the "let task = URLSession.shared.dataTask(with: request as URLRequest){" structure it can execute without the SIGABRT error, but I need it inside so it transfers to the second view only if the user input is correct.

How do i fix this? Thanks in advance.

Keep in mind that i am a beginner to xcode and swift, so sorry if this is a dumb question.


Solution

  • The crash is because you're attempting to perform a segue on a background thread (because the performSegue call is in a URLSession callback). Any code that does things with views needs to run on the main thread.

    Try wrapping your performSegue call in a DispatchQueue block, like this:

    DispatchQueue.main.async {
        self.performSegue(withIdentifier: "LogPers", sender: nil)
    }