【发布时间】:2017-08-08 04:51:49
【问题描述】:
我如何从网站读取 JSON,例如:https://example.com/checkifexists.php?name=test,它会返回如下内容:[{"exists":"true"}] 或 [{"exists":"false"}]。我想检查它是否存在并使用 swift 获取值 true 或 false。
谢谢:)
【问题讨论】:
我如何从网站读取 JSON,例如:https://example.com/checkifexists.php?name=test,它会返回如下内容:[{"exists":"true"}] 或 [{"exists":"false"}]。我想检查它是否存在并使用 swift 获取值 true 或 false。
谢谢:)
【问题讨论】:
我无法实际测试它,因为示例 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()
【讨论】:
[{"exists":"true"}] 或[{"exists":"false"}] 读取真假?
let json = JSON(data: data) 我收到错误Use of unresolved identifier 'JSON'。你知道那是什么吗?