无法在Swift应用程序上解析服务器PHP

时间:2016-03-29 11:43:00

标签: php ios json swift parsing

我正在尝试在我的iOS应用上实现注册/登录功能。 为此,我编写了一个简单的服务器端PHP脚本,只是为了检查它是否返回一个值。 这是我的PHP代码:

<?php

if(isset($_POST["username"])){
$username = $_POST["username"];
$password = $_POST["password"];
if($username == "admin" && $password == "admin")
{
$details;
$details['success'] = $username;
echo json_encode($details);
}
else{
echo "invalid credential";
}
};
?>

以下是登录界面中的代码:

let myUrl = NSURL(string: "http://localhost/app/index.php")  
    let request = NSMutableURLRequest(URL:myUrl!)
    request.HTTPMethod = "POST" 
    request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept") 
    //print("\(usernameField.text!), \(passwordField.text!), \(emailField.text!)")  
    //let params = ["user":"\(usernameField.text!)","pass":"\(passwordField.text!)"] as NSDictionary  
    let bodyData = "username=\(usernameField.text)&password=\(passwordField.text)"  
    request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding)

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: {
            data, response, error in
            do {
                let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary
                print("json is : \(json!)")
                if let parseJSON = json {
                    let firstNameValue = parseJSON["success"] as? String
                    print("Username: \(firstNameValue!)")
                }
            } catch {
                print("errorrrrr: \(error)")
            }  
            if error != nil {
                print("error=\(error!)")
                return
            }        
            // You can print out response object
            print("Response = \(response!)")
            // Print out reponse body
            let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
            print("response Data = \(responseString!)")


        })
        task.resume()

}

但是,我收到以下错误:

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

我的回复数据“凭据无效”

1 个答案:

答案 0 :(得分:4)

您的php脚本不适用于网络服务。它没有返回一个json。您必须先完成Web服务。我不是一个骗子的人。但我还是试着改进剧本:

<?php
if(isset($_POST["username"])){
$username = $_POST["username"];
$password = $_POST["password"];
if($username == "admin" && $password == "admin")
{
    $details;
    $details['success'] = $username;
    return json_encode($details);
}
else{
    return json_encode( array("response" => "invalid credential") );
}
};
?>

更新:在迭代alamofire库后使用以下代码访问webservice:

let parameters = ["username": usernameField.text! ,"password" : passwordField.text! ]

Alamofire.request(.POST, "http://localhost/app/index.php", parameters: parameters)
     .responseString { response in
         print("Response String: \(response.result.value)")
     }
     .responseJSON { response in
         print("Response JSON: \(response.result.value)")
       //Handle the json response here
      if let parseJSON = response.result.value {
                let firstNameValue = parseJSON["success"] as? String
                print("Username: \(firstNameValue!)")
            }
     }