am a beginner in swiftui, still learning how to deal with ObservableObject let me show my code and illustrate what is my question...
JsonResponse as follows:
{
"error" : false,
"user" : {
"username" : "Maxwell",
"id" : 84560,
"name" : "Max",
"authority" : "Manager"
}
}
Authenticate User Class (ObservableObject):
import Foundation
import Alamofire
struct UserDetails{
static var id: String = ""
static var name: String = ""
static var authority: String = ""
}
class AuthenticateUser: ObservableObject{
@Published var isLoggedin: Bool = false
func Authenticate(Username:String,Password:String){
let url:String = "http://…./Login.php"
let headers: HTTPHeaders = ["Content-Type":"application/x-www-form-urlencoded"]
let data: Parameters = ["username":Username,"password":Password]
AF.request(url, method: .post, parameters: data, encoding: URLEncoding.default, headers: headers).validate(statusCode: 200 ..< 299).response { AFdata in
do {
guard let jsonObject = try JSONSerialization.jsonObject(with: AFdata.data!, options: .mutableContainers) as? NSDictionary else {
print("Error: Cannot convert data to JSON object")
return
}
guard let prettyJsonData = try? JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted) else {
print("Error: Cannot convert JSON object to Pretty JSON data")
return
}
guard let prettyPrintedJson = String(data: prettyJsonData, encoding: .utf8) else {
print("Error: Cannot print JSON in String")
return
}
//if there is no error
if(!(jsonObject.value(forKey: "error") as! Bool)){
print(prettyPrintedJson)
//getting the user from response
let user = jsonObject.value(forKey: "user") as! NSDictionary
//getting user values
let userID = user.value(forKey: "id") as! Int
let name = user.value(forKey: "name") as! String
let authority = user.value(forKey: "authority") as! String
//saving user values
UserDetails.id = String(userID)
UserDetails.name = name
UserDetails.authority = authority
self.isLoggedin = true
}else{
//error message in case of wrong credentials
print("Wrong Credentials")
}
} catch {
print("Error: Trying to convert JSON data to string")
return
}
}
}
}
Login View:
import SwiftUI
struct Login: View {
@StateObject private var loginManager = AuthenticateUser()
@State var username = ""
@State var password = ""
var body: some View {
ZStack{
Rectangle()
.fill(Color(red: 33 / 255, green: 34 / 255, blue: 36 / 255))
.frame(maxWidth: .infinity, maxHeight: .infinity)
.edgesIgnoringSafeArea(.all)
VStack(){
Spacer()
Image("Logo")
Spacer()
VStack(){
Text("RIVIERA BEACH CHALETS")
.font(.title2)
.fontWeight(.semibold)
.foregroundColor(.white)
.multilineTextAlignment(.center)
Text("Administration System")
.font(.headline)
.fontWeight(.light)
.foregroundColor(.white)
}
Spacer()
Text("Sign in")
.font(.largeTitle)
.fontWeight(.medium)
.foregroundColor(.white)
Spacer()
VStack(){
ZStack {
if username.isEmpty {
Text("Username")
.foregroundColor(.white.opacity(0.3))
}
TextField("", text: $username)
.padding()
.multilineTextAlignment(.center)
.foregroundColor(.white)
.overlay(RoundedRectangle(cornerRadius: 20).stroke(Color.white,lineWidth: 1))
}.padding(.horizontal,5).padding(.vertical,5)
Spacer().frame(height: 15)
ZStack {
if password.isEmpty {
Text("Password")
.foregroundColor(.white.opacity(0.3))
}
SecureField("", text: $password)
.padding()
.multilineTextAlignment(.center)
.foregroundColor(.white)
.overlay(RoundedRectangle(cornerRadius: 20).stroke(Color.white,lineWidth: 1))
}.padding(.horizontal,5).padding(.vertical,5)
Spacer().frame(height: 15)
HStack {
Button(action:{
//BUTTON ACTION
loginManager.Authenticate(Username: username, Password: password)
},label: {
Spacer()
Text("AUTHENTICATE")
.font(.subheadline)
.fontWeight(.bold)
.foregroundColor(.white.opacity(0.8))
Spacer()
}) .padding()
.background(Color(red: 40 / 255, green: 41 / 255, blue: 43 / 255))
.cornerRadius(20)
}.padding(.horizontal,20).padding(.vertical,5).padding()
Spacer()
}.padding(20)
Spacer()
}
}
}
}
struct LoginPreview: PreviewProvider {
static var previews: some View {
Login()
}
}
let me explain what is going on... and what is my question: As you can see in code, we have a Json Object response being parsed as NS dictionary while revalidating the UserDetails variables with the data from the Json response, and a published Bool to detect whether logged in or not ! so the question is, how to setup that bool to let the view detect whether user logged in or not ... ? in another words ,what to type in the view code to let the app switch the view to Home view for example if logged in was true ... ? while parsing the user details to show it in that Home view.
Any help would be appreciated !