【问题标题】:Can't figure out swift POST request error无法弄清楚快速 POST 请求错误
【发布时间】:2020-04-17 18:12:48
【问题描述】:

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

【问题讨论】:

  • 我做到了,但我收到了这个错误Initializer for conditional binding must have Optional type, not 'serverResponse'

标签: swift swiftui urlsession


【解决方案1】:

看起来您的服务器正在返回 loginResult 而不是 serverResponse。可以试试吗

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

【讨论】:

  • 我明白你的意思,但 JSONDecoder 中的代码没有运行。我添加了一个 do catch,但我在 JSONDecoder 行中得到了Initializer for conditional binding must have Optional type, not 'serverResponse'
  • 没关系,我已修复它,但现在我在主屏幕上的 TabView 中遇到错误。
猜你喜欢
  • 2015-10-26
  • 2012-08-23
  • 1970-01-01
  • 1970-01-01
  • 2016-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多