• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

ios - Swift 如何更新(修改、删除、添加)JSON 条目

[复制链接]
菜鸟教程小白 发表于 2022-12-11 17:52:07 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

您好,我需要一些帮助,我正在制作一个 IOS 应用程序,它从 JSON API 获取数据,然后在表格上显示结果,当我点击表格中的结果时,它会转到第二个 View Controller 我正在展示细节。我想要做的是更新我在详细信息中显示的信息,通过从表本身中删除它们来从 JSON 中删除条目,并添加一个要保存在 JSON 上的新条目。

这是 JSON 结构:

      {
        _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"
        },

我希望能够更新 SSID、密码和摘要。

这是我用来从 JSON 中获取结果的代码,并且运行良好

代码:

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

例如,如果我单击表格的一行,我希望能够更新密码。



Best Answer-推荐答案


我设法做到了:所有格式都为 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 = "OST"


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


            }

        }

关于ios - Swift 如何更新(修改、删除、添加)JSON 条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40094922/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap