So it's my first SwiftUI project and I'm working on a login screen and a signup screen for a personal project and I'm trying to use CoreData to save the User object when a new User is created and to retrieve an existing User object when the user signs in using a predicate.
I'm not sure if I'm going about this the right way but what I did is I initiated the Navigation stack inside of my Login View (first View) and I'm having trouble creating, fetching, and passing a new user into the child View (ContentView) upon clicking the "Sign In" button that's triggered via Navigation Link. I'm not too sure if I should even be using a Navigation link since I cannot Create the User object, fetch it, and then pass it to the destination, all within the NavigationLink. Can someone provide some guidance please? Much appreciated!
Here is the code for my Login View...
import SwiftUI
import CoreData
struct LoginView: View {
@State private var user : String = ""
@State private var pass : String = ""
@State private var isLoginValid: Bool = false
@State private var shoudlShowLoginAlert: Bool = false
@State private var selectedUser:User?
@Environment(\.managedObjectContext) var moc
var body: some View {
NavigationView{
VStack{
Image(uiImage: #imageLiteral(resourceName: "awText"))
.resizable()
.frame(width: 180, height: 100)
.padding(.bottom, 50)
TextField("Username", text: $user)
.padding(.leading)
Divider()
.padding(.bottom)
TextField("Password", text: $pass)
.padding(.leading)
Divider()
NavigationLink(
destination: ContentView(selectedUser: self.selectedUser ?? User()),
isActive: self.$isLoginValid,
label: {
Text("Login")
})
.onTapGesture {
selectedUser = fetchUserDetails(withUser: user)
let isLoginValid = self.user == selectedUser?.username && self.pass == selectedUser?.password
if isLoginValid {
self.isLoginValid = true //trigger NavLink
} else {
self.shoudlShowLoginAlert = true
}
}
.frame(width: 300, height: 50)
.background(Color.green)
.clipShape(RoundedRectangle(cornerRadius: 20, style: .continuous))
.padding()
NavigationLink(
destination: SignUpView(),
label: {
Text("Sign Up")
})
.frame(width: 300, height: 50)
.background(Color.orange)
.clipShape(RoundedRectangle(cornerRadius: 20, style: .continuous))
}
.navigationTitle("AW Support")
.alert(isPresented: $shoudlShowLoginAlert, content: {
Alert(title: Text("Email/Password Incorrect"))
})
}
}
}
func fetchUserDetails(withUser user: String) -> User? {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let fetchRequest = NSFetchRequest<User>(entityName: "User")
fetchRequest.fetchLimit = 1
fetchRequest.predicate = NSPredicate(format: "username == %@", user)
do {
let fetchUser = try context.fetch(fetchRequest)
return fetchUser.first
} catch let fetchError {
print("Failed to fetch: \(fetchError)")
}
return nil
}
struct LoginView_Previews: PreviewProvider {
static var previews: some View {
LoginView()
}
}