Json_encode doesn't trow back any data

Hi everybody, I'm making a little app that make a login on a mysql database, using a php page.

when the application return from the php page I take this 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.}


On the php page, I write some logs and it seems that there is no problem on php page.

I'm using xcode 8 and swift 3.

this is the code of the application:

/

let url = NSURL(string: "

/

let request = NSMutableURLRequest(url: url as URL)

let username = txtusername.text!

let password = txtpassword.text!

/

request.httpMethod = "POST"

/

let body = "username=\(username)&password=\(password)"

request.httpBody = body.data(using: .utf8)

/

URLSession.shared.dataTask(with: request as URLRequest, completionHandler: { (data:Data?, response:URLResponse?, error:Error?) in

if error == nil {

/

DispatchQueue.main.async(execute: {

do {

let json = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions .mutableContainers) as?

NSDictionary

guard let parseJSON = json else {

print ("Error while parsing")

return

}

let id = parseJSON["id"]

if id != nil {

print (parseJSON)

}

} catch {

print ("catch an error: \(error)")

}

})

}else {

print ("error: \(error)")

}

/

}).resume()

}

}

Thanks in advance for your help.

Regards.


Angelo.

Replies

It would help if you edited your post to use a code block (via the

<>
icon). It’s really hard to read your code right now.

With regards the actual error you’re getting, this is pretty self explanatory. By default JSONSerialization expects the JSON’s top-level value to be an array or an object. If it’s something else, you get this error. You can fix that by either fixing your server (in most cases you want to return an array or an object to allow for extensibility in the future) or by setting the

.allowFragments
flag on the parser.

If you run into further problems parsing JSON, please post a hex dump of the data you passed to the parser. You can get a hex dump really easily with code like this:

NSLog("data = %@", data as NSData)

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

Escume Eskimo, excuse me for the code.

Does Nslog works even in xcode8? and whre I have to set the .allowFragments?


here the code with the block.

if txtusername.text!.isEmpty || txtpassword.text!.isEmpty{
            txtusername.attributedPlaceholder = NSAttributedString(string: "Username", attributes: [NSForegroundColorAttributeName: UIColor.red  ])
            txtpassword.attributedPlaceholder = NSAttributedString(string: "Password", attributes: [NSForegroundColorAttributeName: UIColor.red])
        }else{
           
           
            /
           
            let url = NSURL(string: "mywebsite/login.php"  
            / 
            
            let request = NSMutableURLRequest(url: url as URL)
            
            
            let username = txtusername.text!
            let password = txtpassword.text!
            
            / 
            
            request.httpMethod = "POST"
            / 
            let body = "username=\(username)&password=\(password)"
            request.httpBody = body.data(using: .utf8)
            / 
            URLSession.shared.dataTask(with: request as URLRequest, completionHandler: { (data:Data?, response:URLResponse?, error:Error?) in
                NSLog("data = %@", data as Data!)
                
                
                
                
                if error == nil {
                    / 
                    DispatchQueue.main.async(execute: {
                        do {
                            let json = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions .mutableContainers) as?
                            NSDictionary
                            guard let parseJSON = json else {
                                print ("Error while parsing")
                                return
                            }
                            let id = parseJSON["id"]
                            if id != nil {
                                print (parseJSON)
                            }
                        } catch {
                            print ("catch an error: \(error)")
                        }
                    })
                }else {
                print ("error: \(error)")
                }
                / 
                }).resume()
            }
        }

Thank you Eskimo! With NSLOG I've found that in the php code there was an echo that was not commented.