12/4
2023
在 SwiftUI 中,您可以使用组合 Button
、URLSession
和异步 SwiftUI
视图来处理 HTTP GET 请求。以下是一个简单的示例代码:
struct ContentView: View {
@State var result = "等待响应..."
var body: some View {
VStack {
Text(result)
.padding()
Button(action: {
// 点击按钮时发送GET请求
self.fetchDataFromServer()
}) {
Text("获取数据")
.font(.headline)
.foregroundColor(.white)
.padding()
.background(Color.blue)
.cornerRadius(10)
}
}
}
func fetchDataFromServer() {
guard let url = URL(string: "https://jsonplaceholder.typicode.com/todos/1") else {
return
}
URLSession.shared.dataTask(with: url) { data, response, error in
if let data = data {
if let decodedResponse = try? JSONDecoder().decode(Todo.self, from: data) {
DispatchQueue.main.async {
self.result = "用户ID:\(decodedResponse.userId), 标题:\(decodedResponse.title)"
}
return
}
}
DispatchQueue.main.async {
self.result = "请求出错: \(error?.localizedDescription ?? "未知错误")"
}
}.resume()
}
}
struct Todo: Codable {
let id, userId: Int
let title: String
let completed: Bool
}
在这个示例中,我们创建了一个视图层次结构包含有一个标签和一个按钮。当用户点击按钮时,我们会异步地发送一个 HTTP GET 请求,该请求将从 jsonplaceholder
上获取待办事项 (Todo
) 数据并解码返回的 JSON 响应。然后我们将结果显示在标签中。
需要注意的是,由于异步执行,代码可能会更改视图状态和 UI 元素,因此您需要确保在主线程中调用任何更改呈现的内容。在上面的示例中,我们使用 DispatchQueue.main.async
在主线程中更新视图状态以显示结果。