【发布时间】:2016-03-29 11:43:00
【问题描述】:
我正在尝试在我的 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.}
我的响应数据是“无效凭据”。
【问题讨论】:
标签: php ios json swift parsing