此代码的目的是使用PHP脚本将数据发送到SQL数据库。 但是当我尝试运行它时,我收到以下错误:
错误域= NSCocoaErrorDomain代码= 3840" JSON文本不以数组或对象和选项开头,以允许未设置片段。" UserInfo = {NSDebugDescription = JSON文本不是以数组或对象开头,而是选项允许未设置片段。}
这是我的代码:
// 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()
这里有什么问题?
答案 0 :(得分:2)
该错误通常意味着NSData
不包含有效的JSON。
您应该查看response
和data
的字符串表示形式,因为如果服务器遇到问题,很可能会在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)
}
当您查看NSURLResponse
和NSData
个对象时,您将更有可能诊断出问题。
-
顺便说一句,我可能会建议指定请求的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这样的框架来处理这些细节。
答案 1 :(得分:0)
在我的情况下,即使以下代码通过在输出的开头附加额外的//斜杠也会导致此错误。
$arr = array("status" => 1, "msg" => "Your message goes here!");
echo json_encode($arr);
原因是这些额外字符正在我包含在此文件中的其他文件中打印。