我正试图在我的iOS应用程序上实现Signup/Login函数。为此,我编写了一个简单的服务器端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.}
我的响应数据是“无效凭据”。
发布于 2016-03-29 04:49:09
您的php脚本对于webservice没有完成。这不是送回一个json。你必须先完成你的网络服务。我不是个php的家伙。但我还是试图改进剧本:
<?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!)")
}
}
https://stackoverflow.com/questions/36283310
复制相似问题