简体   繁体   中英

Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object

The purpose of this code is to send data to a SQL database using PHP script. But when I try to run it I get the following error:

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

This is my code:

// 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()

What is the problem here?

That error generally means that the NSData doesn't contain valid JSON.

You should look at the response and the string representation of the data because if the server encountered a problem, it most likely would have returned a statusCode in the NSHTTPURLResponse (where 200 means that everything was OK, RFC 2616 describes what the other error codes mean) and the NSData likely contains HTML or text describing the nature of the problem:

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

When you look at the NSURLResponse and NSData objects, you will you be far more likely to diagnose the problem.

--

By the way, I might advise specifying the Content-Type of the request. Also, I'd suggest percent-escaping the email address and password. The latter is important because if the values contain special characters (eg + and & are notable problems), the data will not be processed correctly by the server.

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)

Where

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: "+")
    }
}

Alternatively, you can build the character set of allowed characters by starting with URLQueryAllowedCharacterSet , but you still have to remove a few characters as it will otherwise that allows certain characters pass unescaped (eg + ). See https://stackoverflow.com/a/35912606/1271826 .

Or you could use a framework like Alamofire which takes care of these details for you.

In my case, even the following code was causing this error by appending extra // slashes at the beginning of the output.

$arr = array("status" => 1, "msg" => "Your message goes here!");
echo json_encode($arr);

The reason was that these extra characters were being printed in other file that I included to this file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM