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? - ios

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.

Related

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

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)*/
}
}
}
}

Google signing is signing in automatically, also right after log out. swift 4

After writing the log in with mail, i'm integrating social logins to my app and starting with Google signin. It now logs in automatically at app start, not if I press the Google login button. If I cancel it at pop up window it throws an Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional valueon the token line in AppDelegate`. Also logging out doesn't prevent to log in automatically again.
It was quite confusing following instruction from Firebase manual for Google login so I sure made some obvious mistake.
Here's the code so far:
AppDelegate:
// start google sign in methods
#available(iOS 9.0, *)
func application(_ application: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any])
-> Bool {
return GIDSignIn.sharedInstance().handle(url,
sourceApplication:options[UIApplicationOpenURLOptionsKey.sourceApplication] as? String,
annotation: options[UIApplicationOpenURLOptionsKey.annotation])
}
func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error?) {
// ...
print("User successfully signed in with Google",user)
guard let idToken = user.authentication.idToken else {
return
}
guard let accessToken = user.authentication.accessToken else {return}
let credentials = GoogleAuthProvider.credential(withIDToken: idToken, accessToken: accessToken)
Auth.auth().signInAndRetrieveData(with: credentials) { (user, error) in
if let error = error {
print("Failed to create user with Google account", error)
return
}
print("Succesfully created new user in Firebase with Google account")
}
if let error = error {
// ...
print("User failed to sign in with Google", error)
return
}
guard let authentication = user.authentication else { return }
let credential = GoogleAuthProvider.credential(withIDToken: authentication.idToken,
accessToken: authentication.accessToken)
// let storyboard = UIStoryboard(name: "Main", bundle: nil)
// var mainVC = self.window?.visibleViewController as? MainNavigationController
// mainVC = storyboard.instantiateViewController(withIdentifier: "MainNavigationController") as? MainNavigationController
}
func sign(_ signIn: GIDSignIn!, didDisconnectWith user: GIDGoogleUser!, withError error: Error!) {
// Perform any operations when the user disconnects from app here.
// ...
}
// end of google sign in
The Google signin should perform a segue to main menu but it doesn't.
Only at first sign in it gets to the desired vc.
Here's the Login class:
import UIKit
import Firebase
import GoogleSignIn
class LoginViewController: UIViewController, GIDSignInUIDelegate {
// outlets
#IBOutlet weak var backGroundImage: UIImageView!
#IBOutlet weak var userNameTextField: UITextField!
#IBOutlet weak var emailTextField: UITextField!
#IBOutlet weak var passwordTextField: UITextField!
#IBOutlet weak var confirmPasswordTextField: UITextField!
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if Auth.auth().currentUser != nil {
self.performSegue(withIdentifier: "skipSegue", sender: nil)
}
}
override func viewDidLoad() {
super.viewDidLoad()
setGoogleButton()
setFacebookButton()
}
// dismiss keyboard on touch outside textfields
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for txt in self.view.subviews {
if txt.isKind(of: UITextField.self) && txt.isFirstResponder {
txt.resignFirstResponder()
}
}
}
private func setGoogleButton() {
GIDSignIn.sharedInstance().uiDelegate = self
GIDSignIn.sharedInstance().signIn()
}
private func setFacebookButton() {
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// Actions
#IBAction func newUserRegisterButton(_ sender: Any) {
if passwordTextField.text != confirmPasswordTextField.text{
let alertController = UIAlertController(title: "Password Incorrect", message: "Please re-type password", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
}
else{
Auth.auth().createUser(withEmail: emailTextField.text!, password: passwordTextField.text!){ (user, error) in
if error == nil {
self.performSegue(withIdentifier: "skipSegue", sender: self)
}
else{
let alertController = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
}
}
}
}
#IBAction func mailLogin(_ sender: UIButton) {
Auth.auth().signIn(withEmail: emailTextField.text!, password: passwordTextField.text!) { (user, error) in
if error == nil{
self.performSegue(withIdentifier: "skipSegue", sender: self)
}
else{
let alertController = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
}
}
}
#IBAction func facebookLogin(_ sender: UIButton) {
}
#IBOutlet weak var signInButton: GIDSignInButton!
#IBAction func googleSignInButton(_ sender: GIDSignInButton) {
performSegue(withIdentifier: "skipSegue", sender: self)
}
#IBAction func logoutButton(_ sender: UIButton) {
}
#IBAction func skipButton(_ sender: UIButton) {
performSegue(withIdentifier: "skipSegue", sender: self)
}
}
The sign out:
#IBAction func logOutButton(_ sender: UIButton) {
// firebase auth sign out
let firebaseAuth = Auth.auth()
do {
try firebaseAuth.signOut()
} catch let signOutError as NSError {
print ("Error signing out: %#", signOutError)
}
// GSI log out
GIDSignIn.sharedInstance().signOut()
print("User successfully logged out Firebase with Google account")
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let initial = storyboard.instantiateInitialViewController()
UIApplication.shared.keyWindow?.rootViewController = initial
}
func signOutOverride() {
do {
GIDSignIn.sharedInstance().signOut()
try GIDSignIn.sharedInstance()?.disconnect()
// Set the view to the login screen after signing out
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let initial = storyboard.instantiateInitialViewController()
UIApplication.shared.keyWindow?.rootViewController = initial
// let storyboard = UIStoryboard(name: "SignIn", bundle: nil)
// let loginVC = storyboard.instantiateViewControllerWithIdentifier("SignInVC") as! SignInViewController
// let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
// appDelegate.window?.rootViewController = loginVC
} catch let signOutError as NSError {
print ("Error signing out: \(signOutError)")
}
}
I read many posts about revoking the tokens and disconnect the user from the app, but couldn't implement those solutions as some are in obj-c and others in older swift syntax.
Anyone having same problem as me?
Thank as usual.
After many tries and error,thanks to Google's sarcastically useful documentation, I found out what the problem was. They suggest to put the sign in inside viewDidLoad()' and that obviously get's called every time the VC gets instantiated. I so Moved into the Google sign in button and left the delegate only inviewDidLoad()
It all now works as expected.
override func viewDidLoad() {
super.viewDidLoad()
GIDSignIn.sharedInstance().uiDelegate = self
setFacebookButton()
}
#IBOutlet weak var signInButton: GIDSignInButton!
#IBAction func googleSignInButton(_ sender: GIDSignInButton) {
GIDSignIn.sharedInstance()?.signIn()
performSegue(withIdentifier: "skipSegue", sender: self)
}

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
}

How Keep session in Swift 3.0 using UserDefaults.standard?

I have two(2) swift 3.0 files.
Edited:
My goal is to keep the ViewController active/appear after login is success.
And I want to keep LoginVC active when logout button hit.
Everything works fine such as posting and read json data.
Edited:
ViewController successfully active when loggedin, but when i hit logout button, stop and build it again, ViewController still not dismiss. It should be redirect to LoginVC.
I think maybe something wrong with my UserDefaults.standard code.
My code as below
ViewController.swift
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() { super.viewDidLoad() }
override func viewDidAppear(_ animated: Bool) {
let isUserLoggedIn = UserDefaults.standard.bool(forKey: "isUserLoggedIn")
if(!isUserLoggedIn){
self.performSegue(withIdentifier: "loginview", sender: self)
}
}
#IBAction func logoutData(_ sender: Any) {
UserDefaults.standard.set(true, forKey: "isUserLoggedIn");
UserDefaults.standard.synchronize();
self.performSegue(withIdentifier: "loginview", sender: self)
}
}
LoginVC.swift
import UIKit
class LoginVC: UIViewController {
#IBOutlet var _login: UITextField!
#IBOutlet var _pass: UITextField!
var login: String!
var pass: String!
override func viewDidLoad() { super.viewDidLoad() }
#IBAction func loginData(_ sender: Any) {
login = _login.text
pass = _pass.text
if(login == "" || pass == "") {
return
}
else {
let url = URL(string: "http://localhost/login.php")
let session = URLSession.shared
let request = NSMutableURLRequest(url: url! as URL)
request.httpMethod = "POST"
let paramToLogin = "login=\(login!)&pass=\(pass!)"
request.httpBody = paramToLogin.data(using: String.Encoding.utf8)
let task = session.dataTask(with: request as URLRequest, completionHandler: {
(data, response, error) in
if error != nil {
return
}
else {
do {
if let json = try JSONSerialization.jsonObject(with: data!) as? [String: String]
{
DispatchQueue.main.async {
let success = Int(json["message"]!)
if(success == 1){
UserDefaults.standard.set(true, forKey: "isUserLoggedIn")
UserDefaults.standard.synchronize();
self.dismiss(animated: true, completion: nil)
return
}
}
}
}
catch { }
}
})
task.resume()
}
}
}
In your code during Logout also the value "true" is storing in UserDefaults. I think this may be the issue.
let loginStroyBoard = UIStoryboard(name:"Login", bundle: nil)
let businessLoginViewController = loginStroyBoard.instantiateViewController(withIdentifier: "BusinessLoginViewController") as! BusinessLoginViewController
let refreshAlert = UIAlertController(title: "Log Out", message: "Are You Sure to Log Out ? ", preferredStyle: UIAlertControllerStyle.alert)
refreshAlert.addAction(UIAlertAction(title: "Confirm", style: .default, handler: { (action: UIAlertAction!) in
self.present(businessLoginViewController, animated: true, completion: nil)
DispatchQueue.main.async {
UserDefaults.standard.removeObject(forKey: "isFirstTime")
UserDefaults.standard.removeObject(forKey: "isLogIn")
UserDefaults.standard.removeObject(forKey: "uid")
UserDefaults.standard.removeObject(forKey: "hash")
UserDefaults.standard.removeObject(forKey: "storeadminid")
UserDefaults.standard.removeObject(forKey: "adminhash")
UserDefaults.standard.removeObject(forKey: "store_id")
UserDefaults.standard.removeObject(forKey: "isLogIn")
UserDefaults.standard.removeObject(forKey: "login_id")
UserDefaults.standard.removeObject(forKey: "password")
UserDefaults.standard.setValue(false, forKey: "islogout")
}
//self.tabBarController?.tabBar.resignFirstResponder()
}))
refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: { (action: UIAlertAction!) in
refreshAlert .dismiss(animated: true, completion: nil)
}))
present(refreshAlert, animated: true, completion: nil)
}
I will be using this for logout also..
You can try this one, I will do it with my cell in logout button.

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