【问题标题】:Read external JSON with Swift [closed]使用 Swift 读取外部 JSON [关闭]
【发布时间】:2017-08-08 04:51:49
【问题描述】:

我如何从网站读取 JSON,例如:https://example.com/checkifexists.php?name=test,它会返回如下内容:[{"exists":"true"}][{"exists":"false"}]。我想检查它是否存在并使用 swift 获取值 true 或 false。 谢谢:)

【问题讨论】:

    标签: json swift xcode


    【解决方案1】:

    我无法实际测试它,因为示例 url 实际上并没有返回所需的 JSON [{"exists":"true"}] or [{"exists":"false"}],但我相信这应该可以满足您的需求。

        let urlString = "https://example.com/checkifexists.php?name=test"
        let url = URL(string: urlString)
        URLSession.shared.dataTask(with: url!) { (data, response, error) in
            if error != nil {
                print(error as Any)
            } else {
                do {
                    if let data = data,
                       let json = try JSONSerialization.jsonObject(with: data) as? [[String:String]] {
                        if json[0]["exists"] == "true" {
                            print("it exists")
                        } else {
                            print("it does not exist")
                        }
                    }
                } catch let error as NSError {
                    print(error)
                }
            }
        }.resume()
    

    【讨论】:

    • @MikeKillewald 我真的很感激这一点,但是有没有办法简单地从[{"exists":"true"}][{"exists":"false"}] 读取真假?
    • 我已更新我的答案以阅读您的特定 JSON 示例。我希望这会有所帮助:)
    • 还有一个问题,对不起:p。在这条线上let json = JSON(data: data) 我收到错误Use of unresolved identifier 'JSON'。你知道那是什么吗?
    • “JSON”标识符是我提到的 swiftyJSON.swift 文件中提供的结构。因此,您需要从 GitHub link 下载该文件,然后将其添加到您的项目树中以使其正常工作。此外,您将需要一个实际返回请求的 JSON 位的 url。
    • 感谢您的意见。我是 iOS 开发和 Swift 的初学者。我不专业地编写代码。在离开编程多年后,我最近才回到编程领域(再次只是作为一个业余爱好者)。我正在尝试以我目前掌握的知识以我所知道的最佳方式提供帮助。也就是说,请告诉我你这样做的方式,这样我就可以学习。再次感谢。
    猜你喜欢
    • 2021-07-16
    • 2019-12-05
    • 1970-01-01
    • 2020-09-11
    • 1970-01-01
    • 2020-09-15
    • 1970-01-01
    • 2016-08-15
    • 1970-01-01
    相关资源
    最近更新 更多