问题描述
问题
数据从Reddit的api成功解码并放入.onAppear{…}
内的变量theUser
,但是当我尝试使用它时,我一直得到nil价值.
The data is successfully decoded from Reddit’s api and put into the variable theUser
inside the .onAppear {…}
, but when I try to use it I keep getting nil values.
代码
struct ContentView: View {
@State var didAppear = false
@State var theUser = getNilUser()
var body: some View {
Text("User Profile")
Text(theUser.data.subreddit.display_name_prefixed ?? "No name found")
.onAppear(perform: {
theUser = getUser(withName: "markregg")
})
}
func getUser(withName username: String) -> user {
if !didAppear {
if let url = URL(string: "https://www.reddit.com/user/\(username)/about.json") {
do {
let data = try Data(contentsOf: url)
do {
let decodedUser = try JSONDecoder().decode(user.self, from: data)
return decodedUser
} catch {
print(error)
}
} catch {
print(error)
}
}
didAppear = true
}
return getNilUser()
}
}
我对此很陌生,所以如果我犯了一个愚蠢的错误,我很抱歉
I’m very new to this so if I made a stupid mistake I’m sorry
推荐答案
你不能得到这样的 JSON 数据.您必须使用 URLSession
类执行 HTTP 请求以便获取数据并对其进行解析.
You can't get JSON data like that. You have to execute a HTTP request using the URLSession
class in order to get the data and parse it.
let username = "markregg"
let url = URL(string: "https://www.reddit.com/user/\(username)/about.json")!
URLSession.shared.dataTask(with: url) { data, response, error in
if let error = error {
print(error)
} else if let data = data {
do {
let decodedUser = try JSONDecoder().decode(User.self, from: data)
} catch {
print(error)
}
} else {
print("Request failed")
}
}.resume()
另一件需要注意的事情是 URLSession
方法是异步的.简单来说,这意味着它们需要一些时间来执行并返回结果.因此,您不能使用像 return decodedUser
这样的简单返回语句来立即获得结果.研究如何使用 URLSession
更多.
Another thing to note is that URLSession
methods are asynchronous. In simple terms it means they take some time to execute and return the result. So you can't use a simple return statement like return decodedUser
to get the result right away. Look into how to use URLSession
more.
这篇关于如何在 SwiftUI 中使用从 JSON 解码的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!