Problem using JSONSerialization.jsonObject

Good afternoon guys, I have a project made in Xcode 9.2 and I have this problem, it doesn't record the information, I've already tested the API and ok, but I couldn't find the error yet:

@IBAction func register_click(_ sender: Any) {

        //if not text

        

        if usernameTxt.text!.isEmpty || passwordTxt.text!.isEmpty || emailTxt.text!.isEmpty || firstnameTxt.text!.isEmpty || lastnameTxt.text!.isEmpty {

            usernameTxt.attributedPlaceholder = NSAttributedString(string: "username", attributes: [NSAttributedStringKey.foregroundColor: UIColor.red])

            

            passwordTxt.attributedPlaceholder = NSAttributedString(string: "password", attributes: [NSAttributedStringKey.foregroundColor: UIColor.red])

            

            emailTxt.attributedPlaceholder = NSAttributedString(string: "email", attributes: [NSAttributedStringKey.foregroundColor: UIColor.red])

            

            firstnameTxt.attributedPlaceholder = NSAttributedString(string: "name", attributes: [NSAttributedStringKey.foregroundColor: UIColor.red])

            

            lastnameTxt.attributedPlaceholder = NSAttributedString(string: "surname", attributes: [NSAttributedStringKey.foregroundColor: UIColor.red])

            

        } else {

            // if entered - create new user mysql

            // remove keyboard

            self.view.endEditing(true)

            

            // url to php file

            let url = URL(string: "http://localhost/Twiter/register.php")

            // request to php file

            var request = URLRequest(url: url!)

            // method to pass data to this file (e.g. via  POST)

            request.httpMethod = "POST"

            

            request.addValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")

            request.addValue("application/json", forHTTPHeaderField: "Accept")

            request.setValue( "application/json", forHTTPHeaderField: "Authorization")

            //request.setValue("application/json; application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")

            // body to be appended to url

            let body = "username=(usernameTxt.text!.lowercased())&password=(passwordTxt.text!)&email=(emailTxt.text!)&fullname=(firstnameTxt.text!)%20(lastnameTxt.text!)"

            

            request.httpBody = body.data(using: .utf8) //allowLossyConversion: true

            

            // proceed request URLSession.shared.dataTask(with: request) { data, response, error in

            URLSession.shared.dataTask(with: request) { data, response, error in

                if error == nil {

                    

                    // get main queue in code process to communicate back to UI

                    DispatchQueue.main.async(execute: {

                        do {

                           // get json result

                           let json = try JSONSerialization.jsonObject(with: data!, options:  .mutableContainers) as? NSDictionary

                            

                            // assign json to new var parseJSON in guard/secured way

                            guard let parseJSON = json else {

                                print("Error parsing parsing")

                                return

                            }

                            

                            // get id from parseJSON dictionary

                            let id = parseJSON["id"]

                            

                            // successfully registered

                            if id != nil {

                                //print(parseJSON)

                                DispatchQueue.main.async(execute: {

                                    let message = parseJSON["message"] as! String

                                    appDelegate.infoView(message: message, color: colorLightGreen)

                                   print("Sucesso!")

                                })

                                

                                

                              // error

                            } else {

                                //get main queue to comunicate back to user

                                DispatchQueue.main.async(execute: {

                                    let message = parseJSON["message"] as! String

                                    //appDelegate.errorView(message: message)

                                    appDelegate.infoView(message: message, color: colorSmoothRed)

                                    print("Erro sem sucesso(parseJSON)")

                                })

                            }

                            

                        }

                        

                        catch {

                            DispatchQueue.main.async(execute: {

                                let message = "Erro de Comunicação(error)"

                                appDelegate.infoView(message: message, color: colorSmoothRed)

                            })

                        }

                        

                        

                    })

                  // if unable to proceed request

                } else {

                    // get main queue to comunicate back to user

                    DispatchQueue.main.async(execute: {

                        let message = error!.localizedDescription

                        appDelegate.infoView(message: message, color: colorSmoothRed)

                        print("sem comunicação!")

                    })

                } 

                

            // launch prepared session

            } .resume()

            

        }

        

    }

It would be a lot easier to read your posts if you put the code in a code block. For this and other hints and tips for using DevForums effectively, see Quinn’s Top Ten DevForums Tips.

I have a project made in Xcode 9.2

Does that mean you’re using Xcode 9.2 currently?

Or that the project was originally made with Xcode 9.2 but now you’re trying to get it running with a more modern Xcode?

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Using an example of code block formatting: is the second line here for real, or just a copy/paste error while redacting your code for the forum? —

request.addValue("application/json", forHTTPHeaderField: "Accept")
request.setValue("application/json", forHTTPHeaderField: "Authorization")

Assuming a bad authorization header isn’t the problem, can you be more clear about what is going wrong?

it doesn't record the information

What does that mean exactly? Does the upload execute successfully (without hitting any of the error cases) and the data is simply not available on the backend? Or does it execute one of the error handling cases? If so, which one?

Also (at least for next time) please try to cut down the code to the smallest amount that demonstrates the problem. That makes people more likely to read it and often helps to figure out the problem directly. In this case, the code for validating input and dispatching results to the UI isn’t relevant to the core problem and is best omitted when posting.

Thanks for return Scott.

My backEnd is PHP and it is to register new user:

Problem using JSONSerialization.jsonObject
 
 
Q