NEW: Subscribe to Hacking with Swift+ and accelerate your learning! >>

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

   

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

   

@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

   

Hacking with Swift is sponsored by NSSpain

SPONSORED Announcing NSSpain 2020: Remote Edition! An online, continuous conference for iOS developers. We’ll start on Thursday and finish on Friday, with talks, activities, and lots of fun for 36 hours, non-stop. Sound good? Join us!

Find out more

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

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

Not logged in

Log in
 

Link copied to your pasteboard.