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