无法找出快速的开机自检请求错误



我试图在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还很陌生,用swift黑客攻击得到了GET请求的URLSession,并试图将其转换为POST

看起来您的服务器返回的是loginResult而不是serverResponse。你能试试吗

if let decodedResponse = try? JSONDecoder().decode(loginResult.self, from: data) {
print(decodedResponse)
DispatchQueue.main.async {
self.results = [decodedResponse]
}
return
}

最新更新