Я пытаюсь создать экран входа в SwiftUI, который вызывает сервер через POST-запрос, но я получаю неизвестную ошибку (у меня print("Fetch failed: \(error?.localizedDescription ?? "Unknown error")")
).
Сервер получает запрос и данные в запросе POST и возвращает: {"correctCredentials": true, "message": ""}
, но декодер json не работает, и я не знаю почему, может кто-то взглянуть на мой код?
import SwiftUI
struct serverResponse: Codable {
var loginResults: [loginResult]
}
struct loginResult: Codable {
var correctCredentials: Bool
var message: String
}
struct credentialsFormat: Codable {
var username: String
var password: String
}
struct loginView: View {
func getData() {
guard let url = URL(string: "https://example.com/api/login") else {
print("Invalid URL")
return
}
guard let encoded = try? JSONEncoder().encode(credentialsFormat(username: username, password: password)) else {
print("Failed to encode data")
return()
}
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = encoded
URLSession.shared.dataTask(with: request) { data, response, error in
if let data = data {
print("here")
let status = (response as! HTTPURLResponse).statusCode
print(status)
//if (status == 200) {
if let decodedResponse = try? JSONDecoder().decode(serverResponse.self, from: data) {
// we have good data – go back to the main thread
print("here1")
DispatchQueue.main.async {
// update our UI
self.results = decodedResponse.loginResults
}
// everything is good, so we can exit
return
}
//} else { print("Status is not 200"); return } //from if status == 200
}
// if we're still here it means there was a problem
print("Fetch failed: \(error?.localizedDescription ?? "Unknown error")")
}.resume()
}
@State private var results = [loginResult]()
@State private var username: String = ""
@State private var password: String = ""
@State private var showingAlert: Bool = false
var body: some View {
VStack{
TextField("Username", text: $username)
.textFieldStyle(RoundedBorderTextFieldStyle())
.frame(width: 200, height: nil)
.multilineTextAlignment(.center)
.disableAutocorrection(Bool(true))
.accessibility(identifier: "Username")
.autocapitalization(.none)
SecureField("Password", text: $password)
.textFieldStyle(RoundedBorderTextFieldStyle())
.frame(width: 200, height: nil)
.multilineTextAlignment(.center)
.disableAutocorrection(true)
.accessibility(identifier: "Password")
Button(action: {
self.getData()
//if self.results.correctCredentials {
//self.showingAlert = true
//}
//print(self.username + ", " + self.password)
print(self.results)
}) {
HStack{
Spacer()
Text("Login").font(.headline).foregroundColor(.white)
Spacer()
}.padding(.vertical, CGFloat(10))
.background(Color.red)
.padding(.horizontal, CGFloat(40))
}
.alert(isPresented: $showingAlert) {
Alert(title: Text("Wrong Credentials"), message: Text("The username and/or password that you entered is wrong"), dismissButton: .default(Text("Got it!")))
}
}
}
}
кстати, Я совершенно новичок в swift и получил URLSession для GET-запроса от взлома с помощью swift и попытался преобразовать его в POST