UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

URLSession error

Forums > Swift

I followed this hackingwithswift tutorial to get data from a server and tried to convert it to a POST request for a login screen, I am able to get a value in the server but in the console i get the error: https://www.hackingwithswift.com/books/ios-swiftui/sending-and-receiving-codable-data-with-urlsession-and-swiftui and I don't know how to fix it.

My code is:

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/iphone/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")
                    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
                    }
                }
                // 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!")))
        }
        }
    }
}

the server retruns: {"correctCredentials": true, "message": ""}

Thanks for the help

3      

If what you posted is full server response, then that is basic JSON object and you need to use loginResult with the JSONDecoder and not the serverResponse

3      

@nemecek-flip I see what you mean but the code inside the JSONDecoder is not running. I added a do-catch but I'm getting Initializer for conditional binding must have Optional type, not 'serverResponse' in the JSONDecoder line

Nevermind, I changed the code and it worked. But now im getting an error in my TabView

3      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.