Agung Laksana Agung Laksana - 10 months ago 165
Swift Question

error while doing JSON Serialization ErrorDomain Code=3840

I am trying to delete a post in a table view, but I get an error while doing JSON serialization, in this line

let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [String: AnyObject]


if i access the url through the browser, the data is successfully deleted in the database, and if it is accessed from the browser, it also gives the json response back like this


{"message":"successfully deleted","result":1,"status":"Image has been
deleted from drive"}


but i got an error that says the json text did not start with array or object (code =3840), but as you can see above, it is a json dictionary

enter image description here

here is the full code i use. what went wrong in here? Thanks

func deletePost(_ indexPath: IndexPath) {

let tweet = tweetsArray[indexPath.row]
let uuid = tweet["uuid"] as! String
let imagePath = tweet["imagePath"] as! String




let url = URL(string: "http://localhost/Twitter/post.php")
var request = URLRequest(url: url!)
request.httpMethod = "POST"
let body = "uuid=\(uuid)&path=\(imagePath)"
request.httpBody = body.data(using: String.Encoding.utf8)

let session = URLSession.shared
let task = session.dataTask(with: request) { (data, response, error) in


if error == nil {

do {



let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [String: AnyObject]

guard let parsedJSON = json else {
print("error while parsing JSON")
return
}
=

let jsonMessage = parsedJSON["message"]


if jsonMessage != nil {
// hilangkan data di array
self.tweetsArray.remove(at: indexPath.row)
self.imagesArray.remove(at: indexPath.row)

// hilangkan rownya pada table view
self.tableView.deleteRows(at: [indexPath], with: .automatic)
self.tableView.reloadData()
}



} catch {

// get main queue to communicate back to user
DispatchQueue.main.async(execute: {
let message = "\(error)"
self.showAlert(alertTitle: "sorry", alertMessage: message, actionTitle: "OK")
})
return

}





} else {

// get main queue to communicate back to user
DispatchQueue.main.async(execute: {
let message = "\(error!.localizedDescription)"
self.showAlert(alertTitle: "sorry", alertMessage: message, actionTitle: "OK")
})
return
}






}

task.resume()

Answer Source

You can try to Print out your server response. Please change the code in your catch block like. and identifying an error in server side or not.

Your server data is proper json formate then print out your server data and check a server data is valid or not.

URLSession.shared.dataTask(with: url) { (data, response, error) in

        if let jsonData = data {
            do {
                let parsedData = try JSONSerialization.jsonObject(with: jsonData, options: .mutableLeaves) as! [String: AnyObject]
                if let area = parsedData["AREA"] as? [[String: AnyObject]] {
                    for a in area {
                        print(a["area_name"])
                        print(a["price"])
                    }
                }
            }
            catch let err{
                print("\n\n===========Error===========")
                print("Error Code: \(error!._code)")
                print("Error Messsage: \(error!.localizedDescription)")
                if let data = data, let str = String(data: data, encoding: String.Encoding.utf8){
                    print("Server Error: " + str)
                }
                debugPrint(error)
                print("===========================\n\n")

                debugPrint(err)
            }
        }
        else {
            debugPrint(error as Any)
        }

    }.resume()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download