Login page doesn't work fully it works when segue connected but doesn't check if user is registered or not - ios

Login page doesn't really check for if user is stored in core data and will just go ahead with the segue. It should login only if user is registered in core data else will input error and to go register but register seems to work correctly tho I followed some guides online
I have attached the code please check and give me some suggestion to achieve my task
LoginVC
import UIKit
import CoreData
class LoginVC: UIViewController {
#IBOutlet weak var username: UITextField!
#IBOutlet weak var password: UITextField!
var credits = 200.0
var context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view
fetchData()
}
#IBAction func login(_ sender: Any) {
for acc in userList {
if acc.username == username.text && acc.password == password.text {
currentUser = username.text!
try! context.save()
//performSegue(withIdentifier: "DisplayShop1", sender: nil)
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let next = storyBoard.instantiateViewController(identifier: "DisplayShop1") as! ListingShopVC
next.modalPresentationStyle = .fullScreen
self.present(next, animated: true, completion: nil)
}
else if username.text != acc.username || password.text != acc.password || password.text == "" || username.text == "" {
let alert = UIAlertController(title: "Alert", message: "Please enter the correct credentials", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Dismiss", style: .default, handler: nil))
present(alert, animated: true, completion: nil)
}
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "hellothere" {
let ve = segue.destination as! ListingShopVC
ve.creditsss = credits
}
}
func fetchData(){
userList = try! context.fetch(User.fetchRequest())
}
}
RegisterVC
import UIKit
import CoreData
class RegisterVC: UIViewController {
var context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
var userList: String = ""
#IBOutlet weak var username: UITextField!
#IBOutlet weak var cpassword: UITextField!
#IBOutlet weak var password: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBAction func register(_ sender: Any) {
if username.text != ""{
if password.text != "" {
if password.text == cpassword.text {
let newu = User(context: context)
newu.username = username.text
newu.password = password.text
newu.credit = 200.0
try! context.save()
self.navigationController?.popViewController(animated: true)
}
else {
let alert = UIAlertController(title: "Alert", message: "Please enter values correctly", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Dismiss", style: .default, handler: nil))
present(alert, animated: true, completion: nil)*/
}
}
}
}

Related

Merge user info email/phone number authentication, Firebase firestore with swift

Create a user with Username, email, and password. Then force the user to complete phone number verification before the account is created.
I am designing an app where we would like to make the user sign up by creating a username, password, supply their email address, and then complete phone number verification.
This picture represents the desired flow we would like our user to complete to register their account.
here are our View Controller files:
This is the code for the "Create Account" view, it creates a user in Firebase using email
import UIKit
class CreateAccountVC: UIViewController {
#IBOutlet weak var scrollView: UIScrollView!
#IBOutlet weak var usernameTextfield: UITextField!
#IBOutlet weak var passwordTextfield: UITextField!
#IBOutlet weak var emailTextfield: UITextField!
#IBOutlet weak var confirmPasswordTextfield: UITextField!
#IBOutlet weak var createAccountLbl: UILabel!
#IBOutlet weak var createAccountTextView: UILabel!
#IBOutlet weak var signupBtn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
self.hideKeyboardWhenTappedAround()
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name:UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name:UIResponder.keyboardWillHideNotification, object: nil)
overrideUserInterfaceStyle = .light
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
signupBtn.clipsToBounds = true
signupBtn.layer.cornerRadius = 15
signupBtn.addButtonGradient(didType: true)
}
#objc func keyboardWillShow(notification:NSNotification){
let userInfo = notification.userInfo!
var keyboardFrame:CGRect = (userInfo[UIResponder.keyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
keyboardFrame = self.view.convert(keyboardFrame, from: nil)
var contentInset:UIEdgeInsets = self.scrollView.contentInset
contentInset.bottom = keyboardFrame.size.height
scrollView.contentInset = contentInset
}
#objc func keyboardWillHide(notification:NSNotification){
let contentInset:UIEdgeInsets = UIEdgeInsets.zero
scrollView.contentInset = contentInset
}
#IBAction func alreadyHaveAccountBtnPressed(_ sender: Any) {
// dismiss(animated: true, completion: nil)
// self.performSegue(withIdentifier: "TypePhoneNumberVC", sender: self)
}
#IBAction func signupBtnPressed(_ sender: Any) {
let username = usernameTextfield.text
let email = emailTextfield.text
let password = passwordTextfield.text
signupBtn.isHidden = true
AuthorizationService.instance.registerUser(username: username!, email: email!, password: password!) { (success, err) in
if success{
AuthorizationService.instance.loginUser(withEmail: email!, andPassword: password!) { (success, err) in
if err != nil{
return
}
self.performSegue(withIdentifier: "EnterNumberSegue", sender: self)
print("Sign-up successful")
}
}else{
let alertController = UIAlertController(title: "Error", message: err?.localizedDescription, preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
self.signupBtn.isHidden = false
}
}
}
#IBAction func backBtnPressed(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
}
These next two demonstrate the implementation of the Phone number verification
import UIKit
import Firebase
import FirebaseAuth
class EnterPhoneNumberVC: UIViewController, UITextFieldDelegate{
#IBOutlet weak var backButton: UIButton!
#IBOutlet weak var phoneNumberUITextField: UITextField!
#IBOutlet weak var getCodeButton: UIButton!
let userDefaults = UserDefaults.standard
override func viewDidLoad() {
super.viewDidLoad()
phoneNumberUITextField.delegate = self
let tap = UITapGestureRecognizer(target: self, action: #selector(handle))
view.addGestureRecognizer(tap)
overrideUserInterfaceStyle = .light
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
getCodeButton.clipsToBounds = true
getCodeButton.layer.cornerRadius = 15
getCodeButton.addButtonGradient(didType: true)
}
#objc func handle(tap: UITapGestureRecognizer){
view.endEditing(true)
}
#IBAction func backButtonPressed(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
#IBAction func getCodeButtonPressed(_ sender: Any) {
guard let phoneNumber = phoneNumberUITextField.text else {return}
PhoneAuthProvider.provider().verifyPhoneNumber(phoneNumber, uiDelegate: nil) { (verificationID, error) in
if error == nil {
print(verificationID)
guard let verifyID = verificationID else {return}
self.userDefaults.set(verifyID, forKey:"verificationID")
self.userDefaults.synchronize()
self.performSegue(withIdentifier: "GetCodeSegue", sender: self)
} else {
print("unable to confirm the users phone number", error?.localizedDescription)
}
}
}
import UIKit
import Firebase
import FirebaseAuth
class PhoneNumberVerificationVC: UIViewController, UITextFieldDelegate {
#IBOutlet weak var verifyBtn: UIButton!
#IBOutlet weak var resendCodeBtn: UIButton!
#IBOutlet weak var otpCode: UITextField!
var verificationID: String?
let userDefaults = UserDefaults.standard
override func viewDidLoad() {
super.viewDidLoad()
overrideUserInterfaceStyle = .light
let tap = UITapGestureRecognizer(target: self, action: #selector(handle))
view.addGestureRecognizer(tap)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
verifyBtn.clipsToBounds = true
verifyBtn.layer.cornerRadius = 15
verifyBtn.addButtonGradient(didType: true)
}
#objc func handle(tap: UITapGestureRecognizer){
view.endEditing(true)
}
#IBAction func backBtnPressed(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
#IBAction func verifyBtnPressed(_ sender: Any) {
guard let optCode = otpCode.text else {return}
guard let verificationID = userDefaults.string(forKey: "verificationID") else {return}
let credential = PhoneAuthProvider.provider().credential(withVerificationID: verificationID, verificationCode: optCode)
Auth.auth().signInAndRetrieveData(with: credential) { (success, error) in
if error == nil {
print(success)
self.performSegue(withIdentifier: "VerifiedSegue", sender: self)
print("The user has successfully logged In and is verified!")
} else {
print("Error: Phone number and One time password does not match")
}
}
}

When trying to logout/unwind back to the home screen, why would you get a found nil error if there isn't even an optional?

Line where error is:
self.passwordField.delegate = self
Code from the button:
#IBAction func unwindToRed(_ sender: Any) {
do {
try Auth.auth().signOut()
let ViewController1 = ViewController()
let ViewNavigationController = UINavigationController(rootViewController: ViewController1)
self.present(ViewNavigationController, animated: true, completion: nil)
} catch let err {
print(err)
}
}
This is the relevant homepage code:
class ViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var emailField: UITextField!
#IBOutlet weak var passwordField: UITextField!
var userUID: String!
var databaseRef: DatabaseReference!
override func viewDidLoad() {
super.viewDidLoad()
databaseRef = Database.database().reference()
self.passwordField.delegate = self
self.emailField.delegate = self
emailField.attributedPlaceholder = NSAttributedString(string: "Email",
attributes: [NSAttributedString.Key.foregroundColor: UIColor.gray])
passwordField.attributedPlaceholder = NSAttributedString(string: "Password",
attributes: [NSAttributedString.Key.foregroundColor: UIColor.gray])
}
override func viewDidAppear(_ animated: Bool) {
if let _ = KeychainWrapper.standard.string(forKey: "uid") {
self.performSegue(withIdentifier: "tohome", sender: nil)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func signInPressed(_ sender: Any) {
Auth.auth().createUser(withEmail: (emailField.text ?? ""), password: (passwordField.text ?? "")) { (user, error) in
if let _eror = error {
//something bad happning
print(_eror.localizedDescription )
let alert = UIAlertController(title: "Error", message: "Invalid Entry or Duplicate.", preferredStyle: UIAlertController.Style.alert)
let action = UIAlertAction(title: "Ok", style: .default, handler: nil)
alert.addAction(action)
self.present(alert, animated: true, completion: nil)
}else{
//user registered successfully
print(user as Any)
if let userID = user?.uid {
KeychainWrapper.standard.set((userID), forKey: "uid")
let databaseRef = Database.database().reference()
databaseRef.child("people").child(userID).child("users").setValue(self.emailField.text!)
databaseRef.child("people").child(userID).child("postID").setValue(userID)
self.performSegue(withIdentifier: "tohome", sender: nil)
}
}
}
}
#IBAction func loginInPressed(_ sender: Any) {
Auth.auth().signIn(withEmail: (emailField.text ?? ""), password: (passwordField.text ?? "")) { (user, error) in
if let _eror = error {
//something bad happning
print(_eror.localizedDescription )
let alert = UIAlertController(title: "Error", message: "Incorrect Email or Password.", preferredStyle: UIAlertController.Style.alert)
let action = UIAlertAction(title: "Ok", style: .default, handler: nil)
alert.addAction(action)
self.present(alert, animated: true, completion: nil)
}else{
//user registered successfully
print(user as Any)
if let userID = user?.uid {
KeychainWrapper.standard.set((userID), forKey: "uid")
self.performSegue(withIdentifier: "tohome", sender: nil) }
}
}
}
Problem is hiding in this line:
#IBAction func unwindToRed(_ sender: Any) {
do {
try Auth.auth().signOut()
let ViewController1 = ViewController() // <-- This is the problem
let ViewNavigationController = UINavigationController(rootViewController: ViewController1)
self.present(ViewNavigationController, animated: true, completion: nil)
} catch let err {
print(err)
}
}
Because you are using storyboards to create your views, you should instantiate your view controller from storyboard. To do this right please refer to Creating View Controllers from Storyboard.
If you're new to iOS development or you don't know why this is required please refer to this post which will explain instantiating view controller from storyboard vs. creating new instance.

I am having login page how to authenticate the user using coredata database?

I had created a login page and registration page and saved the registered data in core data database but now I need to authenticate the user so that in order to move to another view controller.
here is my code ....
import UIKit
import CoreData
class ViewController: UIViewController {
#IBOutlet weak var usernameTextField: UITextField!
#IBOutlet weak var passwordTextField: UITextField!
#IBOutlet weak var loginButton: UIButton!
#IBOutlet weak var registerButton: UIButton!
var accounts = [Account]()
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
override func viewDidLoad() {
super.viewDidLoad()
self.getAccountData()
loginButton.layer.cornerRadius = 12.0;
registerButton.layer.cornerRadius = 12.0;
usernameTextField.layer.borderWidth = 1;
usernameTextField.layer.borderColor = UIColor.darkGray .cgColor;
usernameTextField.layer.cornerRadius = 5;
usernameTextField.setValue(UIColor.lightGray, forKeyPath: "_placeholderLabel.textColor");
passwordTextField.layer.borderWidth = 1;
passwordTextField.layer.borderColor = UIColor.darkGray.cgColor;
passwordTextField.layer.cornerRadius = 5;
passwordTextField.setValue(UIColor.lightGray, forKeyPath: "_placeholderLabel.textColor");
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func registerButton(_ sender: Any) {
self.performSegue(withIdentifier: "SecondViewController", sender: nil)
return
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
_ = segue.destination as! SecondViewController
}
#IBAction func loginButton(_ sender: Any) {
if (usernameTextField.text?.isEmpty)! == true
{
let usernamealert = UIAlertController(title: "Warning", message: "Please enter username", preferredStyle: UIAlertControllerStyle.alert)
usernamealert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
self.present(usernamealert, animated: true, completion: nil)
}
if (passwordTextField.text?.isEmpty)! == true {
let passwordalert = UIAlertController(title: "Warning", message: "Please enter password", preferredStyle: UIAlertControllerStyle.alert)
passwordalert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
self.present(passwordalert, animated: true, completion: nil)
}
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let managedContext = appDelegate.persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Account")
do
{
let results = try context.fetch(request)
if results.count > 0
{
for result in results as! [NSManagedObject]
{
if let firstname = result.value(forKey: "firstName") as? String
{
if(usernameTextField.text == firstname)
{
if let password = result.value(forKey: "lastname") as? String
{
if(passwordTextField.text == password)
{
}else{
let passwordalert = UIAlertController(title: "Warning", message: "Wrong password", preferredStyle: UIAlertControllerStyle.alert)
passwordalert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
self.present(passwordalert, animated: true, completion: nil)
}
}
}
}
}
}
}
}
#IBAction func unwindToView(segue: UIStoryboardSegue){}
func getAccountData() {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
do {
accounts = try context.fetch(Account.fetchRequest())
} catch {
print("Fetching Failed")
}
}
Try like this
call this method from viewWillAppear
self.getAccountData()
and put below code in loginButton() method After the validation done
var username = ""
var passString = ""
var checkRecord = false
for item in accounts
{
username = item.value(forKeyPath: "firstName") as! String
passString = item.value(forKeyPath: "lastname") as! String
if username == usernameTextField.text && passwordTextField.text == passString
{
checkRecord = true;
}
}
if checkRecord == true
{
//succesfull authenticate
}
else
{
//show the error message
}

What is the correct way to call this function and pass this array via a segue?

I am trying to pass an array from loginViewController to ViewController using a segue.
The array is communtiesArray and is fetched in this section of code:
let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:AnyObject]
if let arr = json?["communities"] as? [[String:String]] {
self.communitiesArray = arr.flatMap { $0["name"]! }
}
print ("first test: ",self.communitiesArray) // This prints values OK.
As stated, this debug test prints correctly. I now try to pass communities.Array through a segue to ViewController in this function:
override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
if segue.identifier == "loginView" {
let createViewController: ViewController = segue.destination as! ViewController
createViewController.communities = communitiesArray
print("second test: ", communitiesArray) //this prints nothing
}
}
I feel I must going wrong in my use of this as an override funcas it did not seem to get called as print debug does not activate.
This is the full userLogin script:
import UIKit
protocol UsernameSentDelegate {
func userLoggedIn(data: String)
}
class LoginViewController: UIViewController {
var delegate: UsernameSentDelegate? = nil
#IBOutlet weak var userEmailTextField: UITextField!
#IBOutlet weak var userPasswordTextField: UITextField!
#IBOutlet weak var displayUserName: UILabel!
var communitiesArray = [String]()
#IBAction func loginButtonTapped(_ sender: AnyObject)
{
let userEmail = userEmailTextField.text;
let userPassword = userPasswordTextField.text;
if (userPassword!.isEmpty || userEmail!.isEmpty) { return; }
// send user data to server side
let myUrl = URL(string: "http://www.quasisquest.uk/KeepScore/userLogin.php");
var request = URLRequest(url:myUrl!);
request.httpMethod = "POST";
let postString = "email=\(userEmail!)&password=\(userPassword!)";
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
DispatchQueue.main.async
{
if(error != nil)
{
//Display an alert message
let myAlert = UIAlertController(title: "Alert", message: error!.localizedDescription, preferredStyle: UIAlertControllerStyle.alert);
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler:nil)
myAlert.addAction(okAction);
self.present(myAlert, animated: true, completion: nil)
return
}
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:AnyObject]
if let arr = json?["communities"] as? [[String:String]] {
self.communitiesArray = arr.flatMap { $0["name"]! }
}
print ("first test: ",self.communitiesArray) // This print correctly in debug
// retrieve login details and check to see if all ok
if let parseJSON = json {
let returnValue = parseJSON["status"] as? String
if(returnValue != "error")
{
self.delegate?.userLoggedIn(data: userEmail! )
UserDefaults.set(UserDefaults.standard)(true, forKey: "isUserLoggedIn");
self.dismiss(animated: true, completion: nil)
} else {
// display an alert message
let userMessage = parseJSON["message"] as? String
let myAlert = UIAlertController(title: "Alert", message: userMessage, preferredStyle: UIAlertControllerStyle.alert);
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler:nil)
myAlert.addAction(okAction);
self.present(myAlert, animated: true, completion: nil)
}
}
} catch
{
print(error)
}
}
}
task.resume()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
if segue.identifier == "loginView" {
let createViewController: ViewController = segue.destination as! ViewController
createViewController.communities = communitiesArray
print("second test: ", communitiesArray) //this prints nothing
}
}
}
In reference to the error I am receiving as stated in comments section, this is the code from ViewController that contains the variable for line createViewController.communities = sender as? Array
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UsernameSentDelegate {
#IBOutlet weak var scrollView: UIScrollView!
#IBOutlet weak var receiveUsername: UILabel!
#IBOutlet weak var userEmailText: UILabel!
var userEmail: String?
var communities = [String]() // this is the target of the segue
plz perform segue like this
performSegue(withIdentifier: "loginView", sender: self.communitiesArray)
and in prepare for segue
override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
if segue.identifier == "loginView" {
let createViewController: ViewController = segue.destination as! ViewController
createViewController.communities = sender as? Array
}
}

Using Swift and CoreData - users logging in

So I am creating an iOS application and want to allow users to log in and out/register. I am doing this using core Data and currently my program allows users to register, but the data isn't saved so when they try and log in, it says incorrect username/password, in other words, the program isn't recognizing the fact that the user already input their information when creating/registering their account and as a result cannot load the information they input and won't allow the user to log in. This is the code I have for when a user clicks the register button - please help:
import UIKit
import CoreData
class RegisterPageViewController: UIViewController {
#IBOutlet weak var userEmailTextField: UITextField!
#IBOutlet weak var userPasswordTextField: UITextField!
#IBOutlet weak var confirmPasswordTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func registerButtonTapped(sender: AnyObject) {
let userEmail = userEmailTextField.text
let userPassword = userPasswordTextField.text
let userConfirmPassword = confirmPasswordTextField.text
if (userEmail.isEmpty || userPassword.isEmpty || userConfirmPassword.isEmpty) {
displayMyAlertMessage("You haven't filled out all the fields.")
return;
}
if (userPassword != userConfirmPassword) {
displayMyAlertMessage("Passwords do not match.")
return;
}
var appDel: AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
var context:NSManagedObjectContext = appDel.managedObjectContext!
var newUser = NSEntityDescription.insertNewObjectForEntityForName("Users", inManagedObjectContext: context) as NSManagedObject
context.save(nil)
var successAlert = UIAlertController(title: "Alert", message: "Successfully registered.", preferredStyle: UIAlertControllerStyle.Alert)
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) { action in
self.dismissViewControllerAnimated(true, completion: nil)
}
successAlert.addAction(okAction)
self.presentViewController(successAlert, animated: true, completion: nil)
}
#IBAction func haveAnAccountButtonTapped(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
func displayMyAlertMessage(userMessage:String) {
var alert = UIAlertController(title: "Alert!", message: userMessage, preferredStyle: UIAlertControllerStyle.Alert)
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)
alert.addAction(okAction)
self.presentViewController(alert, animated: true, completion: nil)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
If you already have in your *.xcdatamodel file Entity 'Users' with Attributes 'name' and 'password', you need to store data from textField, for example:
...
var newUser = NSEntityDescription.insertNewObjectForEntityForName("Users", inManagedObjectContext: context) as NSManagedObject
newUser.setValue(userEmail, forKey: "name")
newUser.setValue(userPassword, forKey: "password")
context.save(nil)
...
SWIFT 4
We Can Create A Login And SignUp In Swift 4 Using Core Data
Here I am Going to create a New project In Swift 4 With Xcode 9 And Follow Me With An Example Task For Core Data
Create New Project With Select Use CoreData
Create an Entity -User
Add fields - name, age,password,email….Plz Select All the fields type with String
Design Storyboard With Apropriate objects….
Create Login,signup,UserDetails,logout VC’s
Import CoreData For Apropriate Classes
For Connect Views We can Use StoryboardId And Segue For the Views
Create LoginVc
import UIKit
import CoreData
class LoginViewController: UIViewController {
#IBOutlet var nameTextCheck: UITextField!
#IBOutlet var passwordTextCheck: UITextField!
var context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func signUPButtonAction(_ sender: Any) {
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "User")
let searchString = self.nameTextCheck.text
let searcghstring2 = self.passwordTextCheck.text
request.predicate = NSPredicate (format: "name == %#", searchString!)
do
{
let result = try context.fetch(request)
if result.count > 0
{
let n = (result[0] as AnyObject).value(forKey: "name") as! String
let p = (result[0] as AnyObject).value(forKey: "password") as! String
// print(" checking")
if (searchString == n && searcghstring2 == p)
{
let UserDetailsVc = self.storyboard?.instantiateViewController(withIdentifier: "UserDetailsViewController") as! UserDetailsViewController
UserDetailsVc.myStringValue = nameTextCheck.text
self.navigationController?.pushViewController(UserDetailsVc, animated: true)
}
else if (searchString == n || searcghstring2 == p)
{
// print("password incorrect ")
let alertController1 = UIAlertController (title: "no user found ", message: "password incorrect ", preferredStyle: UIAlertControllerStyle.alert)
alertController1.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(alertController1, animated: true, completion: nil)
}
}
else
{
let alertController1 = UIAlertController (title: "no user found ", message: "invalid username ", preferredStyle: UIAlertControllerStyle.alert)
alertController1.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(alertController1, animated: true, completion: nil)
print("no user found")
}
}
catch
{
print("error")
}
}
}
Create SignUpVc
import UIKit
import CoreData
class SignUpViewController: UIViewController {
#IBOutlet var nameText: UITextField!
#IBOutlet var passwordText: UITextField!
#IBOutlet var ageText: UITextField!
#IBOutlet var emailText: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func SignUPAction(_ sender: Any) {
if isValidInput(Input: nameText.text!)
{
if isPasswordValid(passwordText.text!)
{
if isValidEmail(testStr: emailText.text!)
{
let _:AppDelegate = (UIApplication.shared.delegate as! AppDelegate)
let context:NSManagedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let newUser = NSEntityDescription.insertNewObject(forEntityName: "User", into: context) as NSManagedObject
newUser.setValue(nameText.text, forKey: "name")
newUser.setValue(passwordText.text, forKey: "password")
newUser.setValue(emailText.text, forKey: "email")
newUser.setValue(ageText.text, forKey: "age")
do {
try context.save()
} catch {}
print(newUser)
print("Object Saved.")
let alertController1 = UIAlertController (title: "Valid ", message: "Sucess ", preferredStyle: UIAlertControllerStyle.alert)
alertController1.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(alertController1, animated: true, completion: nil)
let UserDetailsVc = self.storyboard?.instantiateViewController(withIdentifier: "logoutViewController") as! logoutViewController
self.navigationController?.pushViewController(UserDetailsVc, animated: true)
}else
{
print("mail check")
let alertController1 = UIAlertController (title: "Fill Email id", message: "Enter valid email", preferredStyle: UIAlertControllerStyle.alert)
alertController1.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(alertController1, animated: true, completion: nil)
}
}
else
{
print("pswd check")
let alertController1 = UIAlertController (title: "Fill the password ", message: "Enter valid password", preferredStyle: UIAlertControllerStyle.alert)
alertController1.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(alertController1, animated: true, completion: nil)
}
}
else
{
print("name check")
let alertController1 = UIAlertController (title: "Fill the Name ", message: "Enter valid username", preferredStyle: UIAlertControllerStyle.alert)
alertController1.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(alertController1, animated: true, completion: nil)
}
}
func isValidInput(Input:String) -> Bool
{
let RegEx = "\\A\\w{3,18}\\z"
let Test = NSPredicate(format:"SELF MATCHES %#", RegEx)
return Test.evaluate(with: Input)
}
func isPasswordValid(_ password : String) -> Bool{
let passwordTest = NSPredicate(format: "SELF MATCHES %#", "^(?=.*[a-z])(?=.*[$#$#!%*?&])[A-Za-z\\d$#$#!%*?&]{3,}")
return passwordTest.evaluate(with: password)
}
func isValidEmail(testStr:String) -> Bool {
// print("validate calendar: \(testStr)")
let emailRegEx = "[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"
let emailTest = NSPredicate(format:"SELF MATCHES %#", emailRegEx)
return emailTest.evaluate(with: testStr)
}
}
Create UserDetailsVC
import UIKit
import CoreData
class UserDetailsViewController: UIViewController {
#IBOutlet var nameText: UITextField!
#IBOutlet var ageText: UITextField!
#IBOutlet var emailText: UITextField!
var context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
var myStringValue : String?
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
showData()
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
func showData()
{
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "User")
request.predicate = NSPredicate (format: "name == %#", myStringValue!)
do
{
let result = try context.fetch(request)
if result.count > 0
{
let nameData = (result[0] as AnyObject).value(forKey: "name") as! String
let agedata = (result[0] as AnyObject).value(forKey: "age") as! String
let emaildata = (result[0] as AnyObject).value(forKey: "email") as! String
nameText.text = nameData
ageText.text = agedata
emailText.text = emaildata
}
}
catch {
//handle error
print(error)
}
}
}

Resources