SwiftUI 小demo之 01 获取笑话并显示

SwiftUI 小demo之 01 获取笑话并显示

代码

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()
        
    }
    
    
}

效果

SwiftUI 小demo之 01 获取笑话并显示_第1张图片
image.png

更多SwiftUI教程和代码关注专栏

  • 请关注我的专栏 SwiftUI教程与源码

你可能感兴趣的:(SwiftUI 小demo之 01 获取笑话并显示)