php - Retrieving json object into xCode comes with a nil value always


I am just trying to get this json connection with my sql. The php file is working fine. Is writes and retrieves when I test it directly.

But on XCode I can only write. When I try to get the json object back it always come back as a nil. The error goes bellow. Any idea what could that be?

NSURLSESSION error - nil NSURLSESSION data - <0a0a3264 36663234 37323334 37383135 65313633 33653764 30383233 34626231 34346262 61653830 3637436f 6e6e6563 74656420 746f2064 61746162 6173656c 6f63616c 686f7374 6c6f6361 6c686f73 74537769 66744170 707b2273 74617475 73223a22 34303022 2c226d65 73736167 65223a22 506c6561 73652063 686f6f73 65206469 66666572 656e7420 656d6169 6c206164 64726573 73227d>

JSON dictionary - nil

json error - Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) UserInfo=0x7f8e88a44d40 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}

import UIKit

class SignupViewController: UIViewController {

    @IBOutlet weak var userEmailAddressTextField: UITextField!
    @IBOutlet weak var userPasswordTextField: UITextField!
    @IBOutlet weak var userRepeatPasswordTextField: UITextField!
    @IBOutlet weak var userFirstnameTextField: UITextField!
    @IBOutlet weak var userLastNameTextField: UITextField!

    override func viewDidLoad() {

        // Do any additional setup after loading the view.

    override func didReceiveMemoryWarning() {
        // Dispose of any resources that can be recreated.

    @IBAction func cancelButtonTapped(sender: AnyObject) {

        self.dismissViewControllerAnimated(true, completion: nil)


    @IBAction func signUpButtonTapped(sender: AnyObject) {

        let userEmail = userEmailAddressTextField.text
        let userPassword = userPasswordTextField.text
        let userPasswordRepeat = userRepeatPasswordTextField.text
        let userFirstName = userFirstnameTextField.text
        let userLastName = userLastNameTextField.text

//        if (userPassword != userPasswordRepeat){
//            self.displayAlertMessage("password do not match")
//        }
//        if (userEmail.isEmpty || userPassword.isEmpty || userFirstName.isEmpty || userLastName.isEmpty){
//            self.displayAlertMessage("All fields required")
//        }

        let myUrl = NSURL(string: "http://localhost/SwiftAppAndMYSQL/scripts/registerUser.php")
        let request = NSMutableURLRequest(URL: myUrl!)

        //let postString = "userEmail=\(userEmail)&userPassword=\(userPassword)&userFirstName=\(userFirstName)&userLastName=\(userLastName)"

        let postString = "userEmail=8&userPassword=90&userFirstName=890&userLastName=809"

        request.HTTPMethod = "POST"
        request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)

        NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in

             println("NSURLSESSION error - \(error)")
             println("NSURLSESSION data - \(data)")


                if error != nil {

                var err:NSError?

                var json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as? NSDictionary

                println("JSON dictionary - \(json)")
                println("json error - \(err!)")
                println("JSON data - \(data)")

                if let parseJSON = json{

                    var userId = parseJSON["userId"] as? String


                    if (userId != nil){

                        let alertController = UIAlertController(
                            title: "Bam!",
                            message: "Registration Sucessful",
                            preferredStyle: UIAlertControllerStyle.Alert)

                        let okAction = UIAlertAction(
                            title: "OK",
                            style: UIAlertActionStyle.Default){
                            (action) in

                            self.dismissViewControllerAnimated(true, completion: nil)


                        self.presentViewController(alertController, animated: true, completion: nil)


                            let errorMessage = parseJSON["Message"] as? String
                            if (errorMessage != nil){



    func displayAlertMessage (message: String){

        let alertController = UIAlertController(title: "Bam!", message: message, preferredStyle: UIAlertControllerStyle.Alert)

        let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)


        self.presentViewController(alertController, animated: true, completion: nil)



Php script i am using


//use MySQLDAO;

require ("../db/MySQLDAO.php");
$config = parse_ini_file('../db/SwiftApp.ini');

$returnValue = array();

if (
        empty($_REQUEST["userEmail"]) ||
        empty($_REQUEST["userPassword"]) ||
        empty($_REQUEST["userFirstName"]) ||
        empty($_REQUEST["userLastName"])) {

    $returnValue["status"] = "400";
    $returnValue["message"] = "Missing required information";
    echo json_encode($returnValue);


$userEmail = htmlentities($_REQUEST["userEmail"]);
$userPassword = htmlentities($_REQUEST["userPassword"]);
$userFirstName = htmlentities($_REQUEST["userFirstName"]);
$userLastName = htmlentities($_REQUEST["userLastName"]);

$salt = openssl_random_pseudo_bytes(16);
$secure_password = sha1($userPassword . $salt);
echo $secure_password;

$dbhost = trim($config["dbhost"]);
$dbuser = trim($config["dbuser"]);
$dbpassword = trim($config["dbpassword"]);
$dbname = trim($config["dbname"]);
$dao = new MySQLDAO($dbhost, $dbuser, $dbpassword, $dbname);  


echo $dao->dbhost;
echo $dao->dbname;

$userDetails = $dao->getUserDetails($userEmail);

    $returnValue["status"] = "400";
    $returnValue["message"] = "Please choose different email address";
    echo json_encode($returnValue);

$result = $dao->registerUser($userEmail, $userFirstName, $userLastName, $secure_password, $salt);

if ($result) {
    $userDetails = $dao->getUserDetails($userEmail);
    $returnValue["status"] = "200";
    $returnValue["message"] = "Sucessfully registered new user";
    $returnValue["userId"] = $userDetails["user_id"];
    $returnValue["userFirstName"] = $userDetails["first_name"];
    $returnValue["userLastName"] = $userDetails["last_name"];
    $returnValue["userEmail"] = $userDetails["email"];

} else {
    $returnValue["status"] = "400";
    $returnValue["message"] = "Could not register user with provided information";


echo json_encode($returnValue);




The data in string format was:

2d6f2472347815e1633e7d08234bb144bbae8067Connected to databaselocalhostlocalhostSwiftApp{"status":"400","message":"Please choose different email address"}

Which is not a valid JSON structure. You have to get only the part surrounded by the{} (and including those{}) before you can cast it into JSON dictionary.

People are also looking for solutions to the problem: php - Where the mail is addressed within Symfony2?


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.