gpt4 book ai didi

php - 错误域 = NSCocoaErrorDomain 代码 = 3840“JSON 文本未以数组或对象开头

转载 作者:行者123 更新时间:2023-12-03 17:38:21 27 4
gpt4 key购买 nike

此代码的目的是使用 PHP 脚本将数据发送到 SQL 数据库。但是当我尝试运行它时,出现以下错误:

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

这是我的代码:

// Send userdata to server side
let myURL = NSURL(string: "http://localhost/userRegister.php");
let request = NSMutableURLRequest(URL:myURL!);
request.HTTPMethod = "POST";
let postString = "email=\(userEmail)&password=\(userPassword)";
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);

// Create the task and execute it

let task = NSURLSession.sharedSession().dataTaskWithRequest(request){
data,response, error in

if error != nil{
print("error=\(error)")
return
}

var err: NSError?

do
{
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary

if let parseJSON = json {

var resultValue = parseJSON["status"] as? String
print("result: \(resultValue)")

var isUserRegisterd:Bool = false;
if(resultValue=="Success")
{
isUserRegisterd = true
}

var messageToDisplay: String = (parseJSON["message"] as? String)!

if(!isUserRegisterd)
{
messageToDisplay = (parseJSON["message"] as? String)!
}

dispatch_async(dispatch_get_main_queue(), {

var myAlert = UIAlertController(title: "Alert", message: messageToDisplay, preferredStyle: UIAlertControllerStyle.Alert);
let okAction = UIAlertAction(title: "Oké", style: UIAlertActionStyle.Default){
action in
self.dismissViewControllerAnimated(true, completion: nil);
}
myAlert.addAction(okAction);
self.presentViewController(myAlert, animated: true, completion: nil);
});
}
}

catch
{
print(error)
}
}

task.resume()

这里有什么问题吗?

最佳答案

该错误通常意味着 NSData 不包含有效的 JSON。

您应该查看 responsedata 的字符串表示形式,因为如果服务器遇到问题,它很可能会在 statusCode 中返回 NSHTTPURLResponse (其中 200 表示一切正常,RFC 2616 描述其他错误代码的意思)并且 NSData 可能包含描述问题性质的 HTML 或文本:

do {
// your code where you `try` parsing the JSON response goes here
} catch {
print(error)

if data != nil {
let string = String(data: data!, encoding: NSUTF8StringEncoding)
print(string)
}

print(response)
}

当您查看 NSURLResponseNSData 对象时,您将更有可能诊断问题。

--

顺便说一下,我可能建议指定请求的 Content-Type。另外,我建议对电子邮件地址和密码进行百分比转义。后者很重要,因为如果值包含特殊字符(例如 +& 是值得注意的问题),服务器将无法正确处理数据。

let url = NSURL(string: "http://localhost/userRegister.php")
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
let encodedEmail = userEmail.stringByAddingPercentEncodingForFormUrlencoded()
let encodedPassword = userPassword.stringByAddingPercentEncodingForFormUrlencoded()
let postString = "email=\(encodedEmail)&password=\(encodedPassword)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)

哪里

extension String {

/// Percent escape value to be added to a HTTP request
///
/// This percent-escapes all characters besize the alphanumeric character set and "-", ".", "_", and "*".
/// This will also replace spaces with the "+" character as outlined in the application/x-www-form-urlencoded spec:
///
/// http://www.w3.org/TR/html5/forms.html#application/x-www-form-urlencoded-encoding-algorithm
///
/// - returns: Return percent escaped string.

func stringByAddingPercentEncodingForFormUrlencoded() -> String? {
let allowedCharacters = NSCharacterSet(charactersInString: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._* ")

return stringByAddingPercentEncodingWithAllowedCharacters(allowedCharacters)?.stringByReplacingOccurrencesOfString(" ", withString: "+")
}
}

或者,您可以从 URLQueryAllowedCharacterSet 开始构建允许字符的字符集,但您仍然需要删除一些字符,否则会允许某些字符以未转义的方式传递(例如 + )。请参阅 https://stackoverflow.com/a/35912606/1271826

或者您可以使用像 Alamofire 这样的框架来为您处理这些细节。

关于php - 错误域 = NSCocoaErrorDomain 代码 = 3840“JSON 文本未以数组或对象开头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33066819/

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