在 Xcode 中,我目前遇到以下错误:
Error Domain=NSCocoaErrorDomain Code=3840 "Garbage at end." UserInfo={NSDebugDescription=Garbage at end.}
当我向我的 php 脚本添加一个函数以从数据库中检索“社区”详细信息时,这才刚刚开始发生。这些详细信息存储在一个数组中。
下一行 echo json_encode($communities);
似乎是导致问题的原因,因为它在没有它的情况下运行良好。下面是完整的 userLogin.php 脚本。该行位于底部。
<?php
require ("Conn.php");
require ("MySQLDao.php");
$email = htmlentities($_POST["email"]);
$password = htmlentities($_POST["password"]);
$returnValue = array();
if(empty($email) || empty($password))
{
$returnValue["status"] = "error";
$returnValue["message"] = "Missing required field";
echo json_encode($returnValue);
return;
}
$secure_password = md5($password);
$dao = new MySQLDao();
$dao->openConnection();
$userDetails = $dao->getUserDetailsWithPassword($email,$secure_password);
if(!empty($userDetails))
{
$returnValue["status"] = "Success";
$returnValue["message"] = "User is registered";
echo json_encode($userDetails);
}else{
$returnValue["status"] = "error";
$returnValue["message"] = "User is not found";
echo json_encode($returnValue);
}
//once logged in run function to get list of communities
$communities = array();
$communities = $dao->getCommunities($email);
echo json_encode($communities);
$dao -> closeConnection();
?>
我已经在浏览器中测试了SQL函数,它返回了正确的值,输出如下:
[{"name":"EnclliffeT"},{"name":"OneWinner"},{"name":"Yesss"},{"name":"Treert"},{"name":"Westbrook"}]
我很确定问题出在 Swift 没有正确接收数组。
这是在用户登录时运行的 Swift 代码,它给出了错误:
@IBAction func loginButtonTapped(_ sender: AnyObject)
{
let userEmail = userEmailTextField.text;
let userPassword = userPasswordTextField.text;
if (userPassword!.isEmpty || userEmail!.isEmpty) { return; }
// send user data to server side
let myUrl = URL(string: "http://www.quasisquest.uk/KeepScore/userLogin.php");
var request = URLRequest(url:myUrl!);
request.httpMethod = "POST";
let postString = "email=\(userEmail!)&password=\(userPassword!)";
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
DispatchQueue.main.async
{
if(error != nil)
{
//Display an alert message
let myAlert = UIAlertController(title: "Alert", message: error!.localizedDescription, preferredStyle: UIAlertControllerStyle.alert);
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler:nil)
myAlert.addAction(okAction);
self.present(myAlert, animated: true, completion: nil)
return
}
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:AnyObject]
// retrieve login details and check to see if all ok
if let parseJSON = json {
let returnValue = parseJSON["status"] as? String
if(returnValue != "error")
{
self.delegate?.userLoggedIn(data: userEmail! )
UserDefaults.set(UserDefaults.standard)(true, forKey: "isUserLoggedIn");
self.dismiss(animated: true, completion: nil)
} else {
// display an alert message
let userMessage = parseJSON["message"] as? String
let myAlert = UIAlertController(title: "Alert", message: userMessage, preferredStyle: UIAlertControllerStyle.alert);
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler:nil)
myAlert.addAction(okAction);
self.present(myAlert, animated: true, completion: nil)
}
}
} catch
{
print(error)
}
}
}
task.resume()
}
最佳答案
你正在输出多个 json block ,这是非法的 json:
if(!empty($userDetails))
...
echo json_encode(...)
} else {
...
echo json_encode(...)
}
...
echo json_encode(...)
一个 JSON 文本 block 只能包含一个 SINGLE json 结构。因为你有两个,所以你有一个 JSON 语法错误。
例如
echo json_encode('hi');
echo json_encode('mom');
产生
"hi""mom"
而且由于 JSON 是 javascript 代码,您基本上是在尝试这样做:
var foo = "hi""mom";
^--syntax error, unexpected string
关于php - 从 php 脚本返回数组到 Swift 时,JSON_encode 导致错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40179146/