error while doing JSON Serialization ErrorDomain Code=3840 - ios

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

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

Related

How to reload new data to UITable when one row data is deleted or updated in swift IOS?

So for I've a UITableView in which I'm showing comments which is fetch from my localhost DB, when a user post comment it's send to localhost and store there and it the same time I reload table and the comment is shown it the time but when a user delete a comment or update a comment then in the DB data is actually deleted or updated but my tableview is not reloading with new data till I close the view and open it again.
following is my code.
This my delete comment code:
#objc func deleteComment(){
ProgressHUD.show("Wait Deleting", interaction: false)
customView.removeFromSuperview()
var commentArray : Dictionary<String, Any> = [:]
commentArray["commentId"] = self.getCommentId
let myUrl = URL(string: "http://127.0.0.1:8000/api/comment/delete");
var request = URLRequest(url:myUrl!)
request.httpMethod = "POST"// Compose a query string
request.addValue("application/json", forHTTPHeaderField: "Content-type")
guard let httpbody = try? JSONSerialization.data(withJSONObject: commentArray, options: []) else { return }
request.httpBody = httpbody
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
if error != nil
{
print("error=\(error)")
return
}
// print out response object
// print("response = \(response)")
//Let's convert response sent from a server side script to a NSDictionary object:
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if let parseJSON = json {
if parseJSON["delete"] != nil{
ProgressHUD.dismiss()
self.alertDeleted()
}else {
if parseJSON["error"] != nil{
ProgressHUD.dismiss()
print(parseJSON["error"] as Any)
}
}
}
} catch {
print(error)
}
}
task.resume()
}
This is delete comment alert.
public func alertDeleted(){
let alertController = UIAlertController(title: "Comment Deleted:", message: "Press Ok to continue.", preferredStyle: .alert)
let confirmAction = UIAlertAction(title: "Ok", style: .default) { (_) in
self.showMatchCommentsApiCall()
}
alertController.addAction(confirmAction)
self.present(alertController, animated: true, completion: nil)
}
This is update comment code.
#objc func updateComment(){
ProgressHUD.show("Wait Upating", interaction: false)
updateCommentView.removeFromSuperview()
var commentArray : Dictionary<String, Any> = [:]
commentArray["commentId"] = self.getCommentId
commentArray["updatedComment"] = textView.text
let myUrl = URL(string: "http://127.0.0.1:8000/api/comment/update");
var request = URLRequest(url:myUrl!)
request.httpMethod = "POST"// Compose a query string
request.addValue("application/json", forHTTPHeaderField: "Content-type")
guard let httpbody = try? JSONSerialization.data(withJSONObject: commentArray, options: []) else { return }
request.httpBody = httpbody
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
if error != nil
{
print("error=\(error)")
return
}
// print out response object
//print("response = \(response)")
//Let's convert response sent from a server side script to a NSDictionary object:
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if let parseJSON = json {
if parseJSON["update"] != nil{
ProgressHUD.dismiss()
self.alertCommentUpdated()
self.showMatchCommentsApiCall()
return
}else {
if parseJSON["error"] != nil{
ProgressHUD.dismiss()
print(parseJSON["error"] as Any)
}
}
}
} catch {
print(error)
}
}
task.resume()
}
My ShowMatchCommentsApiCall() function.
public func showMatchCommentsApiCall(){
ProgressHUD.show("Please Wait", interaction: false)
guard let url = URL(string: "http://127.0.0.1:8000/api/matchComments/\(getMatchId)") else {return}
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let dataResponse = data,
error == nil else {
print(error?.localizedDescription ?? "Response Error")
return }
do{
//here dataResponse received from a network request
let jsonResponse = try JSONSerialization.jsonObject(with:
dataResponse, options: [])
// print(jsonResponse) //Response result
guard let jsonArray = jsonResponse as? [[String: Any]] else {
return
}
//print(jsonArray)
for comments in jsonArray{
guard let commentID = comments["commentId"] as? Int else { return }
guard let userID = comments["userId"] as? Int else { return }
guard let userName = comments["userName"] as? String else { return }
let userImgUrl = comments["userImg"] as? String
if userImgUrl != nil{
self.commentsUserImgUrl.append(userImgUrl!)
}else {
self.commentsUserImgUrl.append("nil")
}
guard let commentMessage = comments["comment"] as? String else { return }
self.commentId.append(commentID)
self.commmentsUserId.append(userID)
self.commentsUserName.append(userName)
self.comments.append(commentMessage)
}
} catch let parsingError {
print("Error", parsingError)
}
DispatchQueue.main.async {
self.MatchScoreTable.reloadData()
ProgressHUD.dismiss()
}
}
task.resume()
}
STEP 1. :self.commentsArray.remove(at: indexPath.row)
STEP 2. : self.tableView.deleteRows(at:[indexPath],with:UITableViewRowAnimation.automatic)
STEP 3. : self.tableView.reloadData()
After deleting or updating data just call a UITableView method reloadData
Syntax is as follows :
tableView.reloadData()

Json parsing using URLSession not working

Iam getting an error while i try to send the POST request in swift 3. Any one please suggest me the correct syntax for URLSession.shared method in swift 3. this is what i tried. iam new here.
let task = URLSession.shared.dataTask(with: request, completionHandler: {
(data, response, error) in
if error != nil{
print("error");
return
}
do{
let myjson = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if let parsejson = myjson{
var msg: String!
msg = parsejson["message"] as! String?
print(msg)
}catch error {
print ("")
}
}
})
task.resume().
Here's working URLSession.shared code. I don't have your URL so I used one that is online, free, and produces JSON:
let someURL = URL(string:"https://jsonplaceholder.typicode.com/posts/2")!
let request = URLRequest(url: someURL)
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if error != nil {
print("error")
return
}
guard let data = data else {
print("No data")
return
}
do {
if let myjson = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? Dictionary<String,Any> {
if let title = myjson["title"] {
print("Title was \"\(title)\"")
}
}
} catch {
print("Error parsing JSON: \(error)")
}
}
task.resume()
This outputs Title was "qui est esse" for me.

JSON conversion is getting failed

Please review my code am badly stuck on this issue.
JSON conversion is not happening & it is going into catch block & printing 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.}
I've tried everything which is suggested here on StackOverflow but no luck.
I've trimmed my code for better understanding.
import Foundation
class Server
{
class func convertStringToDictionary(_ data: Data) -> [String:Any]?
{
do
{
let convertedDict = try JSONSerialization.jsonObject(with: data, options: []) as? [String:Any]
return convertedDict
}
catch let error as NSError
{
print(error)
}
return nil
}
class func registerUser( userInfo: String)
{
let url = URL(string: "http://132.148.18.11/missedprayers/welcome/register")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
let postString = "request=" + userInfo
request.httpBody = postString.data(using: .utf8)
//----------------------------------------
let task = URLSession.shared.dataTask(with: request)
{
data, response, error in
guard let data = data, error == nil
else
{
print("error=\(error)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200
{
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
//--------------
let finalData = Server.convertStringToDictionary(data)
print(finalData)
}
task.resume()
}
func submitBtnTapped(_ sender: AnyObject)
{
let userInfoDict = [
"name":"Maaz Patel",
"phoneNum":"+91899885623",
"email":"maaz#gmail.com",
"city":"pune",
"country":"India",
"dobEnglish":"11-02-1992",
"app":"Dalail",
"aqeeda":"Sufi",
"gender":"male",
"MCCycle":""
]
//-------------------
do
{
let jsonData = try JSONSerialization.data(withJSONObject: userInfoDict, options: [] )
let jsonStr = String.init(data: jsonData, encoding: String.Encoding.utf8)
Server.registerUser(userInfo: jsonStr!)
}
catch let error as NSError
{
print(error)
}
}
}
Consider "SubmitBtnTapped" function is getting called from somewhere.
When am trying on Postman it's working also on Android same web service is working fine.

how to access array inside json object in swift

Can't access json object which is array inside json object
i want to access data from json object which have array inside array
and that json file is also uploaded
so pls can anyone check and help me how to get "weather.description"
data
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: "http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=13ae70c6aefa867c44962edc13f94404")!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil {
print("some error occured")
} else {
if let urlContent = data {
do{
let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers)
let newValue = jsonResult as! NSDictionary
print(jsonResult)
let name = newValue["name"]
//Here i am getting name as variable value
//this is not working
let description = newValue["weather"]??[0]["description"]
//this is not working
let description = newValue["weather"]!![0]["description"]
print()
}catch {
print("JSON Preocessing failed")
}
}
}
}
task.resume()
}
I have edited your code a bit, and added a few comments. Basiclly, lets check for the types of your response structure, and get the desired value.
let url = URL(string: "http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=13ae70c6aefa867c44962edc13f94404")!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil {
print("some error occured")
} else {
if let urlContent = data {
do{
let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers)
// I would not recommend to use NSDictionary, try using Swift types instead
guard let newValue = jsonResult as? [String: Any] else {
print("invalid format")
return
}
// Check for the weather parameter as an array of dictionaries and than excess the first array's description
if let weather = newValue["weather"] as? [[String: Any]], let description = weather.first?["description"] as? String {
print(description)
}
}catch {
print("JSON Preocessing failed")
}
}
}
}
task.resume()

A JSON parsing error occurred, here are the details:

Code
func callAddWithPOST(Name mname:String, PhoneNo mphone:String, Email memail:String, Comment mcomments:String){
var names = [String]()
let login = ["countryId":"1"]
print("Your Result is : = \(login)")
let url = NSURL(string: "http://photokeeper.mgtcloud.co.uk/commonwebservice.asmx/getStateList")!
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: url)
do {
let auth = try NSJSONSerialization.dataWithJSONObject(login, options: .PrettyPrinted)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.HTTPMethod = "POST"
request.HTTPBody = auth
let task = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
let badJsonString = "This really isn't valid JSON at all"
let badJsonData = badJsonString.dataUsingEncoding(NSUTF8StringEncoding)!
do {
let parsed = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments)
print(parsed)
let otherParsed = try NSJSONSerialization.JSONObjectWithData(badJsonData, options: NSJSONReadingOptions.AllowFragments)
}
catch let error as NSError {
print("A JSON parsing error occurred, here are the details:\n \(error)")
}
print("Done.")
})
task.resume()
} catch {
print("Error")
}}
OUTPUT
{
d = "{\"result\":[{\"stateId\":3871,\"stateName\":\"Aberdeenshire\"},{\"stateId\":3872,\"stateName\":\"Anglesey/Sir Fon\"},{\"stateId\":3873,\"stateName\":\"Angus\"},{\"stateId\":3874,\"stateName\":\"Antrim\"},{\"stateId\":3875,\"stateName\":\"Argyll And Bute\"},{\"stateId\":3876,\"stateName\":\"Armagh\"},{\"stateId\":3877,\"stateName\":\"Ayrshire\"},{\"stateId\":3878,\"stateName\":\"Bedfordshire\"},{\"stateId\":3879,\"stateName\":\"Berkshire\"},{\"stateId\":3880,\"stateName\":\"Blaenau Gwent/Blaenau Gwent\"},{\"stateId\":3881,\"stateName\":\"Bristol\"},{\"stateId\":3882,\"stateName\":\"Buckinghamshire\"},{\"stateId\":3883,\"stateName\":\"Caerphilly/Caerffili\"},{\"stateId\":3884,\"stateName\":\"Cambridgeshire\"},{\"stateId\":3885,\"stateName\":\"Cardiff/Caerdydd\"},{\"stateId\":3886,\"stateName\":\"Cardiganshire/Ceredigion\"},{\"stateId\":3888,\"stateName\":\"Carmarthenshire/Sir Gaerfyrddin\"},{\"stateId\":3890,\"stateName\":\"Cheshire\"},{\"stateId\":3891,\"stateName\":\"Clackmannanshire\"},{\"stateId\":3893,\"stateName\":\"Conwy/Conwy\"},{\"stateId\":3895,\"stateName\":\"County Durham\"},{\"stateId\":3896,\"stateName\":\"Cumbria\"},{\"stateId\":3897,\"stateName\":\"Denbighshire/Sir Ddinbych\"},{\"stateId\":3898,\"stateName\":\"Derbyshire\"},{\"stateId\":3899,\"stateName\":\"Devon\"},{\"stateId\":3901,\"stateName\":\"Dorset\"},{\"stateId\":3902,\"stateName\":\"Down\"},{\"stateId\":3904,\"stateName\":\"Dumfries And Galloway\"},{\"stateId\":3905,\"stateName\":\"Dunbartonshire\"},{\"stateId\":3906,\"stateName\":\"Dundee\"},{\"stateId\":3907,\"stateName\":\"Durham/North Yorkshire\"},{\"stateId\":3908,\"stateName\":\"East Lothian\"},{\"stateId\":3909,\"stateName\":\"East Sussex\"},{\"stateId\":3910,\"stateName\":\"East Yorkshire\"},{\"stateId\":3911,\"stateName\":\"Edinburgh\"},{\"stateId\":3912,\"stateName\":\"Essex\"},{\"stateId\":3913,\"stateName\":\"Fermanagh\"},{\"stateId\":3914,\"stateName\":\"Fife\"},{\"stateId\":3915,\"stateName\":\"Flintshire/Sir Fflint\"},{\"stateId\":3917,\"stateName\":\"Glamorgan/Morgannwg\"},{\"stateId\":3918,\"stateName\":\"Glasgow\"},{\"stateId\":3919,\"stateName\":\"Gloucestershire\"},{\"stateId\":3920,\"stateName\":\"Gwynedd/Gwynedd\"},{\"stateId\":3921,\"stateName\":\"Hampshire\"},{\"stateId\":3922,\"stateName\":\"Herefordshire\"},{\"stateId\":3923,\"stateName\":\"Hertfordshire\"},{\"stateId\":3924,\"stateName\":\"Highland\"},{\"stateId\":3925,\"stateName\":\"Kent\"},{\"stateId\":3929,\"stateName\":\"Lanarkshire\"},{\"stateId\":3930,\"stateName\":\"Lancashire\"},{\"stateId\":3932,\"stateName\":\"Leicestershire\"},{\"stateId\":3935,\"stateName\":\"Lincolnshire\"},{\"stateId\":3936,\"stateName\":\"London\"},{\"stateId\":3937,\"stateName\":\"Londonderry\"},{\"stateId\":3940,\"stateName\":\"Manchester\"},{\"stateId\":3943,\"stateName\":\"Merthyr Tydfil/Merthyr Tydfil\"},{\"stateId\":3944,\"stateName\":\"Midlothian\"},{\"stateId\":3946,\"stateName\":\"Monmouthshire/Sir Fynwy\"},{\"stateId\":3947,\"stateName\":\"Moray\"},{\"stateId\":3948,\"stateName\":\"Neath Port Talbot\"},{\"stateId\":3949,\"stateName\":\"Newport\"},{\"stateId\":3950,\"stateName\":\"Norfolk\"},{\"stateId\":3951,\"stateName\":\"Northamptonshire\"},{\"stateId\":3952,\"stateName\":\"Northumberland\"},{\"stateId\":3953,\"stateName\":\"Nottinghamshire\"},{\"stateId\":3955,\"stateName\":\"Orkney\"},{\"stateId\":3956,\"stateName\":\"Oxfordshire\"},{\"stateId\":3957,\"stateName\":\"Pembrokeshire/Sir Benfro\"},{\"stateId\":3958,\"stateName\":\"Perth And Kinross\"},{\"stateId\":3959,\"stateName\":\"Powys/Powys\"},{\"stateId\":3960,\"stateName\":\"Renfrewshire\"},{\"stateId\":3962,\"stateName\":\"Rutland\"},{\"stateId\":3963,\"stateName\":\"Scottish Borders\"},{\"stateId\":3964,\"stateName\":\"Shetland Isles\"},{\"stateId\":3965,\"stateName\":\"Shropshire\"},{\"stateId\":3967,\"stateName\":\"Somerset\"},{\"stateId\":3968,\"stateName\":\"South Yorkshire\"},{\"stateId\":3969,\"stateName\":\"Staffordshire\"},{\"stateId\":3970,\"stateName\":\"Stirling\"},{\"stateId\":3971,\"stateName\":\"Suffolk\"},{\"stateId\":3972,\"stateName\":\"Surrey\"},{\"stateId\":3973,\"stateName\":\"Swansea\"},{\"stateId\":3975,\"stateName\":\"Torfaen\"},{\"stateId\":3976,\"stateName\":\"Tyrone\"},{\"stateId\":3977,\"stateName\":\"Warwickshire\"},{\"stateId\":3979,\"stateName\":\"West Lothian\"},{\"stateId\":3980,\"stateName\":\"West Midlands\"},{\"stateId\":3981,\"stateName\":\"West Sussex\"},{\"stateId\":3982,\"stateName\":\"West Yorkshire\"},{\"stateId\":3983,\"stateName\":\"Western Isles\"},{\"stateId\":3987,\"stateName\":\"Wiltshire\"},{\"stateId\":3988,\"stateName\":\"Worcestershire\"},{\"stateId\":3989,\"stateName\":\"Wrexham\"}],\"status\":\"success\"}";
}
A JSON parsing error occurred, here are the details:
Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}
Done.
I AM GETTING ERROR - Invalid value around character 0. I want to get data in proper format with desired key and value, will anybody please help me to fix this issues.
Your JSON response is corrupted. Use JSONLint to verify it.
Convert it from
{\"result\":[{\"stateId\":3871,\"stateName\":\"Aberdeenshire\"}
to
{
"result": {
"stateId": 3871,
"stateName": "Aberdeenshire"
}
}
Notice the removal of the backslashes.
Looks like you are getting String in your response, so try something like this.
do {
let parsed = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! [String: AnyObject]
let responseStr = parsed["d"] as! String
let correctData = responseStr.dataUsingEncoding(NSUTF8StringEncoding)
let responseDic = try NSJSONSerialization.JSONObjectWithData(correctData, options: NSJSONReadingOptions.AllowFragments) as! [String: AnyObject]
print(responseDic)
}
catch let error as NSError {
print("A JSON parsing error occurred, here are the details:\n \(error)")
}
Try this,
if let result:String = parsed["d"]! {
let result = convertStringToDictionary(text: result)
print("Converted result = \(result)")
}
//SWIFT 3
func convertStringToDictionary(text: String) -> [String:AnyObject]? {
if let data = text.data(using: String.Encoding.utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? [String:AnyObject]
} catch let error as NSError {
print(error)
}
}
return nil
}
//SWIFT 2
func convertStringToDictionary(text: String) -> [String:AnyObject]? {
if let data = text.dataUsingEncoding(NSUTF8StringEncoding) {
do {
return try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject]
} catch let error as NSError {
print(error)
}
}
return nil
}

Resources