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: 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: "") else {
                print("Invalid URL")

            guard let encoded = try? JSONEncoder().encode(credentialsFormat(username: username, password: password)) else {
                print("Failed to encode data")

            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 {
                    if let decodedResponse = try? JSONDecoder().decode(serverResponse.self, from: data) {
                        // we have good data – go back to the main thread
                        DispatchQueue.main.async {
                            // update our UI
                            self.results = decodedResponse.loginResults

                        // everything is good, so we can exit
                // if we're still here it means there was a problem
                print("Fetch failed: \(error?.localizedDescription ?? "Unknown error")")

    @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 {
        TextField("Username", text: $username)
        .frame(width: 200, height: nil)
        .accessibility(identifier: "Username")

        SecureField("Password", text: $password)
        .frame(width: 200, height: nil)
        .accessibility(identifier: "Password")

        Button(action: {
            //if self.results.correctCredentials {
                //self.showingAlert = true
            //print(self.username + ", " + self.password)
        }) {
            }.padding(.vertical, CGFloat(10))
            .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.