Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift How to update (modify, Delete, Add) entries of JSON

Tags:

json

ios

swift

Hello i need some help here, I'm making an IOS app that gets data from a JSON API and then showing the results on a Table , when i tap on a result from the table it goes to a second view controller where i'm showing the details. What I want to do is to update the info I'm showing on the details, delete entries from the JSON by deleting them from the table itself, and add a new entry to be saved on the JSON.

This is the JSON structure:

      {
        _id: "57eec6c9dfc2fb03005c0dd0",
        ssid: "nonummy",
        password: "accumsan",
        lat: 29.39293,
        lon: 115.71771,
        summary: "curae nulla dapibus dolor vel est donec odio justo sollicitudin ut",
        __v: 0,
        likes: 1,
        unlikes: 0,
        bssid: "EF:CD:AB:56:34:12"
        },

I want to be able to update the SSID, Password and Summary.

this is the code I'm using to get the Result from the JSON and is working good

Code:

       let url = URL(string:"https://fierce-peak-97303.herokuapp.com/api/wifi")!

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

        if error != nil {

            print(error)

        }else {

            if let urlContent = data {

                do {

                    let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers)

                //print(jsonResult))

                    for item in(jsonResult as? NSArray)! {

                        let ssid = (item as? NSDictionary)?["ssid"] as? NSString

                        //print(ssid)

                    }
                    self.tableData = jsonResult as! NSArray

                    DispatchQueue.main.sync(execute: {
                    self.table.reloadData()
                    })

                }catch {

                    print("No Json Result Was Found")
                }

            }

        }
    }

    task.resume()

For example if I click on one line of the table I want to be able to update password.

like image 201
Calitox Avatar asked Nov 20 '22 14:11

Calitox


1 Answers

I managed to do it like this : all formatted for swift 3

       //declare parameter as a dictionary which contains string as key and  value combination.
    let parameters = ["ssid": newSSID.text!,"password": newPass.text!,"lat": newLat.text!,"lon": newLon.text!,"summary": newSum.text!] as Dictionary<String, String>

    //create the url with NSURL
    let url = URL(string: "https://fierce-peak-97303.herokuapp.com/api/wifi")

    //create the session object

    let session = URLSession.shared

    //now create the NSMutableRequest object using the url object

    let request = NSMutableURLRequest(url: url!)

    request.httpMethod = "POST"


    var err : NSError?
    do {
        request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: [])
    }catch{
        print("error")
    }

    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")

    //create dataTask using the session object to send data to the server

    let task = session.dataTask(with: request as URLRequest, completionHandler: {data, response, error -> Void in
        print("Response: \(response)")
        let strData = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
        print("Body: \(strData)")
        var err: NSError?
        do {
            var json = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) as? NSDictionary

        }catch{

            print("JSON error")
        }

        // Did the JSONObjectWithData constructor return an error? If so, log the error to the console
        if(err != nil) {
            print(err!.localizedDescription)
            let jsonStr = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
            print("Error could not parse JSON: '\(jsonStr)'")
        }
        else {
            // The JSONObjectWithData constructor didn't return an error. But, we should still
            // check and make sure that json has a value using optional binding.

            do {
                let json = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) as? NSDictionary

                if let parseJSON = json {
                    // Okay, the parsedJSON is here, let's get the value for 'success' out of it
                    let success = parseJSON["success"] as? Int
                    print("Success: \(success)")

                }
                else {
                    // Woa, okay the json object was nil, something went worng. Maybe the server isn't running?
                    let jsonStr = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
                    print("Error could not parse JSON: \(jsonStr)")
                }

            }catch{

                print("JSON error")


            }

        }
like image 174
Calitox Avatar answered Jun 07 '23 07:06

Calitox