Wednesday, August 26, 2026
HomeiOS Developmentios - Authentication Error within the login display utilizing Swift decodable encodable

ios – Authentication Error within the login display utilizing Swift decodable encodable

[ad_1]

New to iOS app constructing utilizing swiftui and relaxation api to construct a brand new app. After going by means of many artilces and so on wrote this for login display

SignIn class

    import Basis

   enum AuthenticationError: Error{
    case invalidCredentials
    case customized(errorMessage : String)
     }

 class SignIn {


   struct LoginRequest : Codable
  {
      let UserName : String
      let Password : String
  }

struct LoginResponse : Codable
{
    let AuthToken : String?
    let Message : String?
    let IsSuccess : Bool?
}

  func SignInUser(UserName : String, Password : String, completion : @escaping (Consequence<String, 
   AuthenticationError>)->Void)
   {
    guard let url = URL(string: "http://xx.xxx.xxx.x:port/api/residence/login")
            else
            {
                completion(.failure(.customized(errorMessage: "Invalid URL")))
                return
            }
    
    let physique = LoginRequest (UserName: UserName, Password: Password)
    
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.setValue("software/json", forHTTPHeaderField: "Settle for")
    request.addValue("software/json", forHTTPHeaderField: "Content material-Kind")
    let encodeData = strive? JSONEncoder().encode(physique)
    print(String(information: encodeData!, encoding: .utf8)!)
    request.httpBody = encodeData
    
    URLSession.shared.dataTask(with: request) {(information, response, error) in
        
        guard let information = information , error == nil else
        {
            completion(.failure(.customized(errorMessage: "No Knowledge")))
            return
        }
        
        guard let loginResponse = strive? JSONDecoder().decode(LoginResponse.self, from: information)
                else
                {
                    completion(.failure(.invalidCredentials))
                    return
                }
        guard let token = loginResponse.AuthToken else
        {
            completion(.failure(.invalidCredentials))
            return
        }
        
        completion(.success(token))
        
    }.resume()


 }
 }

SignInViewModel

  import Basis

  class SignInViewModel : ObservableObject {
    @Revealed  var username : String = ""
    @Revealed  var password : String = ""

func LogIn()
{
    SignIn().SignInUser(UserName: username, Password: password)
 {  **Line:#17**   
        end in
        change consequence{
        case .success(let token):
            print(token)
        case .failure(let error):
            print(error.localizedDescription)
        }
      }
   }
}

SignInActivity

import SwiftUI

  struct SignInActivity: View {
@StateObject non-public var loginVM = SignInViewModel()

@State non-public var Username:String = ""
@State non-public var Password:String = ""

var physique: some View {
    VStack(){
        
        Picture("emblem").resizable().aspectRatio(contentMode:.match)
        Spacer()
       
        Textual content("Welcome! Signal In to Proceed ")
            .font(.system(measurement: 20)).fontWeight(.semibold)
            .foregroundColor(Shade.blue)
       Spacer()
        
        VStack(){
            
        HStack(alignment: .middle){
            
            Picture(systemName: "particular person.circle.fill")
                .foregroundColor(Shade.blue)
                .padding(.main,8)
               
            TextField(
                "username", textual content:$loginVM.username)
                .font(.system(measurement: 14))
                .padding(.high,10)
                .padding(.backside,10)
               
             
            
             //   .overlay(VStack{
             //       Divider().offset(x:0,y:15)
             //   })
                
        }.background(Shade("text_bg"))
                .cornerRadius(10)
            .padding(.trailing,25)
            .padding(.main,25)
            .padding(.backside,15)
            .textInputAutocapitalization(.by no means)
            .disableAutocorrection(true)
       
                      
       
        
        HStack(alignment: .middle)
        {
            Picture(systemName: "lock.circle.fill")
                .foregroundColor(Shade.inexperienced)
                .padding(.main,8)
            TextField(
                "password", textual content:$loginVM.password
            ).font(.system(measurement: 14))
                .padding(.high,10)
                .padding(.backside,10)
           //     .overlay(VStack{
           //     Divider().offset(x:0,y:15)
           // })
                
                
        }.background(Shade("text_bg"))
                .cornerRadius(10)
        .padding(.trailing,25)
        .padding(.main,25)
        .textInputAutocapitalization(.by no means)
        .disableAutocorrection(true)
        
        }
       
        HStack()
        {
            Button(motion: {
                loginVM.LogIn()
            })
            {
            Textual content("Signal In")
                    .padding(7)
                    .font(Font.system(measurement: 15))
                    
.foregroundColor(.white).background(Shade.inexperienced).cornerRadius(6).shadow(radius: 5)
        }
        }.padding(.high)
        Spacer()
        Spacer()
    
       
    }.ignoresSafeArea(.keyboard)
    
}

The API is working high quality as I’ve already made the whole app in android(launched) and it working high quality. Now making an attempt to made the app for iOS.

On debug the error is

completion  ()  0x0000000106b27820 ScreenLearning`closure #1 (Swift.Consequence<Swift.String, 
 ScreenLearning.AuthenticationError>) -> () in ScreenLearning.SignInViewModel.LogIn() -> () at 
  SignInViewModel.swift:17

on run the error is AutheticationError 1.

Cant work out what’s going on.

[ad_2]

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments