gpt4 book ai didi

swift - 再次从 swift 3 中的 url 获取 mySql 数据

转载 作者:行者123 更新时间:2023-11-30 12:23:41 26 4
gpt4 key购买 nike

我已经问过这个看似非常简单直接的问题好几次了,但从未得到解决方案。

我有一个获取mySql数据的url

// 1. get url
let url = URL(string:"http://www.mobwebplanet.com/phpWebService/sample.php")

// 2. Fetch data from url
let data = try? Data(contentsOf: url!)
//playground Output is: 102 bytes. So obviously xcode gets the response data from the URL.

然后我继续提取数据:

//3. Create a dictionary from data:
let urlDict = try? JSONSerialization.jsonObject(with: data!, options: [])

// playground Output is: [["Latitude": "37.331741", "Address": "1 Infinite Loop Cupertino, CA", "Name": "Apple", "Longitude": "-122"]]
print(urlDict!)

// playground Output is: "(\n {\n Address = "1 Infinite Loop Cupertino, CA";\n Latitude = "37.331741";\n Longitude = "-122";\n Name = Apple;\n }\n)\n"

我的理解是urlDictAny类型。我说得对吗?

我最大的问题是如何(强制转换或转换)urlDict 以便我可以使用 key=>value 访问该值?像这样:

 urlDict!["Address"] Outputs "1 Infinite Loop Cupertino, CA"
urlDict!["Latitude"] Outputs "37.331741"...

我是 Swift 的新手,所以我这样做是为了练习,任何帮助将不胜感激。

最佳答案

您的 JSON 响应返回一个 Dictionary 对象数组。所以你只需要正确地转换即可。

let urlString = "http://www.mobwebplanet.com/phpWebService/sample.php"
let url = URL(string: urlString)!

let data = try? Data(contentsOf: url)

if let json = try? JSONSerialization.jsonObject(with: data!, options: []) as? [[String:Any]] {
for location in json! {
print(location["Longitude"])
print(location["Latitude"])
print(location["Address"])
}
}

输出:

Optional(-122)
Optional(37.331741)
Optional(1 Infinite Loop Cupertino, CA)

关于swift - 再次从 swift 3 中的 url 获取 mySql 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44484608/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com