SwiftUI3.0 使用URLSession
2022-02-09 本文已影响0人
Johnson_9d92
SwiftUI 使用URLSession
import SwiftUI
struct ContentView: View {
@State private var text = ""
var body: some View {
VStack {
Text(text).font(.title)
Button(action: {
self.startLoad()
}) {
Text("Start").font(.largeTitle)
}
Button(action: {
self.text = ""
}) {
Text("Clear").font(.largeTitle)
}
}
}
func startLoad() {
let url1 = URL(string: "https://github.com/xiaoyouxinqing/PostDemo/raw/master/PostDemo/Resources/PostListData_recommend_1.json")!
let url = URL(string: "http://localhost:8080/PostListData_recommend_1.json")!
var request = URLRequest(url: url)
/* request.timeoutInterval = 15
request.httpMethod = "GET"
let dic = ["key": "value"]
let data = try! JSONSerialization.data(withJSONObject: dic, options: .prettyPrinted)
request.httpBody = data
request.addValue("application/json", forHTTPHeaderField: "Content-Type")*/
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let error = error {
self.updateText(error.localizedDescription)
return
}
guard let httpResponse = response as? HTTPURLResponse,
httpResponse.statusCode == 200 else {
self.updateText("Invalid response")
return
}
guard let data = data else {
self.updateText("No data")
return
}
guard let list = try? JSONDecoder().decode(PostList.self, from: data) else {
self.updateText("Can not parse data")
return
}
self.updateText("Post count \(list.list.count)")
}
task.resume()
}
func updateText(_ text: String) {
DispatchQueue.main.async {
self.text = text
}
}
}
模型:
import Foundation
struct PostList: Codable {
var list: [Post]
}
struct Post: Codable, Identifiable {
let id: Int
let avatar: String // image name
let vip: Bool
let name: String
let date: String // yyyy-MM-dd HH:mm:ss
var isFollowed: Bool
let text: String
let images: [String] // image names
var commentCount: Int
var likeCount: Int
var isLiked: Bool
}