尝试从 php 脚本获取 Json 数据时出错

Error when trying to get Json data from php script

我尝试获取数据时出现以下错误。在互联网上我读到这是因为 php 脚本无效并且没有 return json 数据。但是 php 脚本运行良好并输出正确的数据。

错误信息:

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.}

我试图允许片段,但后来我收到了另一条错误消息。

这是我尝试获取数据的 swift 代码:

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()

这是 php 文件的重要部分:

$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 return 当我打印它时: 数组 ( [status] => 200 [userFirstName] => Paul [userLastName] => Heinemeyer [userEmail] => paul_heine [userId] => 63 )

当你正确格式化你的 PHP 代码时,你会看到,在其他部分你有

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

结果是

failed{...}

正如错误信息已经指出的,这个"JSON text did not start with array or object ..."

也许另一个 if 部分有类似的输出。