无法找出快速的POST请求错误

时间:2020-04-17 18:12:48

标签: swift swiftui urlsession

我正在尝试在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

1 个答案:

答案 0 :(得分:0)

您的服务器似乎正在返回loginResult而不是serverResponse。您可以尝试

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