0

I get the following error when i try to get data. In the internet i read that its because the php script is invalid and don't return json data. But the php script runs fine and outputs the right data.

Error Message :

Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}

I tried to allow fragments but then i get just another error message.

Here is the swift code where i try to get the data :

let myUrl = NSURL(string: "http://xxxxxxxxxxx.xxx/xxxxxxxx.php")

let request = NSMutableURLRequest(URL: myUrl!)
request.HTTPMethod = "POST"

let postString = "userEmail=\(userEmail!)&userPassword=\(userPassword!)"

request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)

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

    dispatch_async(dispatch_get_main_queue())
    {
        if(error != nil)
        {
            var alert = UIAlertController(title: "Achtung", message: error?.localizedDescription, preferredStyle: UIAlertControllerStyle.Alert)

            let action = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil)

            alert.addAction(action)

            self.presentViewController(alert, animated: true, completion: nil)
        }
        print("1")
        do {
            let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary

            if let parseJSON = json {

                let userId = parseJSON["userId"] as? String
                if( userId != nil)
                {
                    print("SUCESS FUCKER")
                    let mainView = self.storyboard?.instantiateViewControllerWithIdentifier("main") as! FlickrPhotosViewController

                    let mainPageNavi = UINavigationController(rootViewController: mainView)
                    //open mainView
                    let appdele = UIApplication.sharedApplication().delegate
                    appdele?.window??.rootViewController = mainPageNavi


                } else {
                    let userMassage = parseJSON["message"] as? String
                    let myAlert = UIAlertController(title: "Alert", message: userMassage, preferredStyle: UIAlertControllerStyle.Alert);

                    let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)
                    myAlert.addAction(okAction);
                    self.presentViewController(myAlert, animated: true, completion: nil)

                }

            }
        } catch{
            print(error)
            print("FAILED CATCHED")
        }

    }
}).resume()

and this is the important part of the php file :

$userSecuredPassword = $userDetails["user_password"];

$userSalt = $userDetails["salt"];

if($userSecuredPassword === sha1($userPassword . $userSalt))
{
    $returnValue["status"]="200";

    $returnValue["userFirstName"] = $userDetails["first_name"];

    $returnValue["userLastName"] = $userDetails["last_name"];

    $returnValue["userEmail"] = $userDetails["email"];

    $returnValue["userId"] = $userDetails["user_id"];
} else {
    $returnValue["status"]="403";

    $returnValue["message"]="User not found";

     echo "failed";

    echo json_encode($returnValue);

    return;
}



echo json_encode($returnValue);

$returnValue returns this when i print it: Array ( [status] => 200 [userFirstName] => Paul [userLastName] => Heinemeyer [userEmail] => paul_heine [userId] => 63 )

1
  • 1
    A few unrelated observations: 1. You really should be percent escaping the values you add to the body of the post request (e.g. if your password had a & or + character in it, it would not be captured correctly). 2. You may want to include a header("Content-Type: application/json"); in php. It's not technically required, but it's good practice. 3. You should also set the Content-Type of the original request to application/x-www-form-urlencoded. 4. Consider using Alamofire to get you out of the weeds of properly creating request and parseing the response. Commented Aug 21, 2016 at 16:11

1 Answer 1

2

When you properly format your PHP code, you will see, that in the else part you have

echo "failed";
echo json_encode($returnValue);

which results in

failed{...}

As the error message already says, this "JSON text did not start with array or object ..."

Maybe there is similar output for the other if part.

Sign up to request clarification or add additional context in comments.

5 Comments

Sry, but i don't understand your solution, so because of those two lines of code i go into a failed block ? @Olaf Dietsche
This is not a solution, just an observation, that in the else case the PHP output does start with "failed", which is neither the start of an array [, nor the start of an object {. So for the else case, remove echo "failed".
To investigate this fully, you must output the response on the client side. There you will see, what the problem is and where the incorrect output comes from. From the partial code in your question, I can deduce only a partial answer.
I solved that problem, the json-dict catched all data, so also my debug echos and that won't work. But thank you for help :)
You are my hero these days :))

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.