I am trying insert into db use post method in swift
and i can not get the response.statusCode of post method in swiftui view
how can i fix it
import SwiftUI
struct ContentView: View {
@State var resp:Int = 0
var body: some View {
VStack{
Text("Hello, World!")
Button(action: {
self.resp = postAdd()
print("view\(self.resp)")
}) {
Text(/*@START_MENU_TOKEN@*/"Button"/*@END_MENU_TOKEN@*/)
.background(self.resp == 201 ? Color.green : Color.gray)
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
func postAdd() ->Int{
let url = URL(string: "http://localhost:3000/user")
var request = URLRequest(url: url!)
var resp = 0
request.httpMethod = "POST"
let urlstr = "id=5&name=aaa"
request.httpBody = urlstr.data(using: .utf8)!
let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
if error == nil, let data = data, let response = response as? HTTPURLResponse {
print("Content-Type: \(response.allHeaderFields["Content-Type"] ?? "")")
print("statusCode: \(response.statusCode)")
resp = response.statusCode
print(String(data: data, encoding: .utf8) ?? "")
}
}.resume()
return resp
}