I’m making a easy login app with customized error message show in an alert for API response failure. Under is my code
@State personal var username = ""
@State personal var password = ""
@State personal var isPresentederror = false
var physique: some View {
NavigationView{
ZStack{
VStack{
TextField("Username", textual content : $username)
.autocapitalization(.none)
.padding()
.body(width:300,top: 50)
SecureField("Password", textual content : $password)
.padding()
.body(width:300,top: 50)
Button("Login"){
authenticateUser(username: username, password: password)
}
.foregroundColor(.white)
.body(width: 300, top: 50)
.background(Shade.blue)
.cornerRadius(10)
.alert("Error", isPresented: $isPresentederror, actions: {
}, message: {
Textual content("One thing went flawed! Please strive once more")
})
}
}
.navigationBarHidden(true)
}
}
on Click on of LOGIN button I’m calling a operate authenticateUser by passing username and password as a parameter
Under is my authenticateUser operate code
func authenticateUser(username: String, password: String){
let technique = "POST"
let urlString = "http://myapi_to verify_username_password"
var urlHeader=//header half goes right here
let json: [String: Any] = ["password": password,
"username": username]
let jsonData = strive? JSONSerialization.information(withJSONObject: json)
urlHeader.httpBody = jsonData
URLSession.shared.dataTask(with: urlHeader) { (information, response , error) in
guard let information = information else { return }
print(String(information: information, encoding: .utf8) ?? "Invalid JSON")
do {
//success code working high-quality
} catch {
print("Error:(error.localizedDescription)")
print(error)
isPresentederror = true
}
}.resume()
}
success is working high-quality for me, however on error I’m displaying an alert with handbook textual content “One thing went flawed! Please strive once more”.
I wish to present an error message coming from API.
the road
print(String(information: information, encoding: .utf8) ?? "Invalid JSON")
in above operate offers an object as under
{"timestamp":"2022-09-30T10:03:29.142+00:00","standing":501,"error":"Please confirm the information you've despatched Discovered","path":"path_to_url"}
I wish to present the error inside alert which is “Please confirm the information you’ve despatched Discovered” coming from API.
I attempted decoding it and UTF technique nevertheless it all the time offers me an error. so please assist me to attain this