gpt4 book ai didi

php - iOS 应用程序接收格式正确的 JSON,但仍然返回为不以数组或对象开头

转载 作者:行者123 更新时间:2023-11-30 12:57:58 26 4
gpt4 key购买 nike

所以基本上我的服务器上有一个登录脚本,它根据用户凭据是否正确或错误返回结果,并且我有一个 iOS 应用程序将数据发送到该登录脚本以返回正确或错误的结果。

这是我的登录页面的相关部分,显示返回代码($userDetails 是正确或错误凭据的 TRUE 或 FALSE 检查):

$userDetails = $dao->getUserDetailsWithHashedPassword($email,$password);
if($userDetails===TRUE) {
$returnValue["status"] = "Success";
$returnValue["message"] = "User logged in !";
echo json_encode($returnValue);
} else {
$returnValue["status"] = "error";
$returnValue["message"] = "User not found";
echo json_encode($returnValue);
}

如果有人需要查看 getUserDetailsWithHashedPassword() 的作用,click here

使用 Postman 测试 HTTP POST,一切正常,在正文中发布 email@email.com 和 testpassword 并使用正确的 Content-Type (application/x-www-form-urlencoded) 时,我得到了正确的结果:

{"status":"error","message":"User not found"}

现在我的 iOS 应该用这段代码来解释它:

@IBAction func loginButtonPressed(_ sender: AnyObject) {
let userEmail = emailLoginField.text
let userPassword = passwordLoginField.text
// Check for empty fields
if((userEmail?.isEmpty)! || (userPassword?.isEmpty)!) {
// Display alert message
displayMyAlertMessage(userMessage: "All fields are required");
return ;
}
// Send user data to server side
let myUrl = URL(string: "https://support.vincentsolutions.ca/userLogin.php");
var request = URLRequest(url:myUrl!);
request.httpMethod = "POST";
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
let postString = "email=\(userEmail!)&password=\(userPassword!)";
request.httpBody = postString.data(using: String.Encoding.utf8);

URLSession.shared.dataTask(with: request, completionHandler: { (data:Data?, response:URLResponse?, error:Error?) -> Void in
if error != nil {
print ("error=\(error)")
return
}
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if let parseJSON = json {
var resultValue = parseJSON["status"] as? String
print("result: \(resultValue)")
var isUserLoggedIn:Bool = false;
if(resultValue=="Success") {
// Login is successful
UserDefaults.standard.set(true, forKey: "isUserLoggedIn");
UserDefaults.standard.synchronize();
self.performSegue(withIdentifier: "loginSuccesful", sender: self)
}
var messageToDisplay:String = parseJSON["message"] as! String!;
if(!isUserLoggedIn) {
messageToDisplay = parseJSON["message"] as! String!;
}
DispatchQueue.main.async(execute: {
// Display alert message with confirmation.
var myAlert = UIAlertController(title: "Alert", message: messageToDisplay, preferredStyle: UIAlertControllerStyle.alert);

let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.default){ action in
self.dismiss(animated: true, completion: nil);
}
myAlert.addAction(okAction);
self.present(myAlert, animated: true, completion: nil);
});
}
} catch let error as NSError {
print("An error occured: \(error)")
}
}).resume()

现在,当我从 iOS 应用程序运行代码时,出现此错误:

An error occured: Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set."

有人看出这里出了什么问题吗?我尝试在此处和互联网上查找该错误,但找不到与我的情况相关的任何内容。

最佳答案

这是因为您从 URL 收到的响应可能不是正确的 JSON 格式。我建议你做两件事 -

  1. 尝试 NSLog 数据和响应
  2. 试试这个

让 json = 尝试 NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) 作为! NS字典

关于php - iOS 应用程序接收格式正确的 JSON,但仍然返回为不以数组或对象开头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40194437/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com