Demo.swift
ContentView.swift
App.swift
import SwiftUI
import Foundation
struct NewTodo: Encodable { let title: String; let completed: Bool }
func createTodo(_ todo: NewTodo) async throws -> Int {
let url = URL(string: "https://jsonplaceholder.typicode.com/todos")!
var req = URLRequest(url: url)
req.httpMethod = "POST"
req.setValue("application/json", forHTTPHeaderField: "Content-Type")
req.httpBody = try JSONEncoder().encode(todo)
let (_, resp) = try await URLSession.shared.data(for: req)
return (resp as? HTTPURLResponse)?.statusCode ?? 0
}
struct NetworkingPostDemo: View {
@State private var status: Int? = nil
var body: some View {
VStack(spacing: 12) {
Button("Create Todo") {
Task {
do { status = try await createTodo(NewTodo(title: "Demo", completed: false)) }
catch { print(error); status = nil }
}
}
if let status { Text("Status: \(status)") }
}
.padding()
}
}
import SwiftUI
struct ContentView: View {
var body: some View {
NetworkingPostDemo()
}
}
import SwiftUI
@main
struct MyApp: App {
var body: some Scene {
WindowGroup { ContentView() }
}
}