import SwiftUI
struct Joke: Codable,Identifiable{
let id = UUID()
var joke: String
var status: Int
}
struct ContentView: View {
@State private var jokes: [Joke] = []
var body: some View {
NavigationView {
VStack {
List {
ForEach(jokes) { joke in
Text(joke.joke)
}
}
.navigationBarTitle(Text("ICanHazDadJokes"))
Button(action: {self.getJoke()},
label: {Text("Get Another Joke")})
}
}
.onAppear(perform: { self.getJoke() }) }
func getJoke() {
let url = URL(string: "https://icanhazdadjoke.com/")!
var urlRequest = URLRequest(url:url)
urlRequest.addValue("text/plain",forHTTPHeaderField: "Accept")
URLSession.shared.dataTask(with: urlRequest) { data, response, error in
if let data = data,
let httpResponse = response as? HTTPURLResponse, (200..<300) ~= httpResponse.statusCode,
let strData = String(bytes: data, encoding: .utf8)
{
print(strData)
self.jokes.insert(Joke(joke: strData, status: 20), at: 0)
} }.resume()
}
}
009_swiftui_获取网络请求并展示
最新推荐文章于 2022-09-24 19:22:59 发布