0

In Xcode I am currently getting the following error:

Error Domain=NSCocoaErrorDomain Code=3840 "Garbage at end." UserInfo={NSDebugDescription=Garbage at end.}

This has just started happening when I added a function to my php script to retrieve 'community' details from the database. These details are stored in an array.

The following line echo json_encode($communities); appears to be causing the problem as it runs fine without it. Below is the full userLogin.php script. That line is at the bottom.

<?php

require ("Conn.php");
require ("MySQLDao.php");

$email = htmlentities($_POST["email"]);
$password = htmlentities($_POST["password"]);

$returnValue = array();


if(empty($email) || empty($password))
{
$returnValue["status"] = "error";
$returnValue["message"] = "Missing required field";
echo json_encode($returnValue);
return;
}

$secure_password = md5($password);

$dao = new MySQLDao();
$dao->openConnection();
$userDetails = $dao->getUserDetailsWithPassword($email,$secure_password);

if(!empty($userDetails))
{
$returnValue["status"] = "Success";
$returnValue["message"] = "User is registered";
echo json_encode($userDetails);
}else{

$returnValue["status"] = "error";
$returnValue["message"] = "User is not found";
echo json_encode($returnValue);
}

//once logged in run function to get list of communities

$communities = array();
$communities = $dao->getCommunities($email);
echo json_encode($communities);

$dao -> closeConnection();

?>

I have tested the SQL function in the browser and it returns the correct values, output below:

[{"name":"EnclliffeT"},{"name":"OneWinner"},{"name":"Yesss"},{"name":"Treert"},{"name":"Westbrook"}]

I'm pretty sure then that the issue is with Swift not receiving the array properly.

This is the Swift code that runs when the user logs in, which gives the error:

 @IBAction func loginButtonTapped(_ sender: AnyObject)
    {

    let userEmail = userEmailTextField.text;
    let userPassword = userPasswordTextField.text;

    if (userPassword!.isEmpty || userEmail!.isEmpty) { return; }

// send user data to server side

    let myUrl = URL(string: "http://www.quasisquest.uk/KeepScore/userLogin.php");

    var request = URLRequest(url:myUrl!);
    request.httpMethod = "POST";
    let postString = "email=\(userEmail!)&password=\(userPassword!)";
    request.httpBody = postString.data(using: String.Encoding.utf8);

    let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
        DispatchQueue.main.async
            {

               if(error != nil)
                {

                    //Display an alert message
                    let myAlert = UIAlertController(title: "Alert", message: error!.localizedDescription, preferredStyle: UIAlertControllerStyle.alert);
                    let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler:nil)
                    myAlert.addAction(okAction);
                    self.present(myAlert, animated: true, completion: nil)
                    return
                }

                do {

                    let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:AnyObject]


                    // retrieve login details and check to see if all ok

                    if let parseJSON = json {

                        let returnValue = parseJSON["status"] as? String

                        if(returnValue != "error")
                        {
                         self.delegate?.userLoggedIn(data: userEmail! )
                         UserDefaults.set(UserDefaults.standard)(true, forKey: "isUserLoggedIn");
                         self.dismiss(animated: true, completion: nil)

                        } else {
                            // display an alert message
                            let userMessage = parseJSON["message"] as? String
                            let myAlert = UIAlertController(title: "Alert", message: userMessage, preferredStyle: UIAlertControllerStyle.alert);
                            let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler:nil)
                            myAlert.addAction(okAction);
                            self.present(myAlert, animated: true, completion: nil)
                        }

                    }
                } catch
                {
                    print(error)
                }

        }

    }

    task.resume()

}
0

1 Answer 1

1

You're outputting MULTIPLE json blocks, which is illegal json:

if(!empty($userDetails))
   ...
   echo json_encode(...)
} else {
   ...
   echo json_encode(...)
}
...
echo json_encode(...)

A block of JSON text can contain only one SINGLE json structure. Since you have two, you have a JSON syntax error.

e.g.

echo json_encode('hi');
echo json_encode('mom');

produces

"hi""mom"

And since JSON IS javascript code, you're basically trying to do this:

var foo = "hi""mom";
              ^--syntax error, unexpected string
Sign up to request clarification or add additional context in comments.

3 Comments

I see. So this is because of the php script trying to output json_encode($communities); and json_encode($returnValue); ? What would be the best solution?
build a SINGLE structure. $data['status'] = true; $data['message'] = 'Success'; $data['data'] = ...data you want to return, then have the client code check that status field and go from there.
My aim is to carry the array across so I can display the contents in a UITableView. Would the method you mention above be suitable for that as different users would be members of differing numbers of 'communities'?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.