Here Is The Login View Controller File Which Has SQLite Queries And Validation…
import UIKit
import CoreData
class LoginVC: UIViewController,UITextFieldDelegate {
@IBOutlet weak var userName: UITextField!
@IBOutlet weak var Password: UITextField!
var results:Array<Any> = []
var db = Database()
var loginSuccess = Bool()
var loggedInUser:String!
var alert = UIAlertController(title: "Error", message: "Something is not right", preferredStyle: .alert)
var OkAction = UIAlertAction(title: "ok", style: .default, handler: nil)
override func viewDidLoad() {
super.viewDidLoad()
alert.addAction(OkAction)
results = db.selectAll(fromTable: "select * from users") as Array
if !results.isEmpty {
print("got the result from mainvc = \(results)")
}
userName.delegate = self
Password.delegate = self
userName.text = "jay"
Password.text = "12345678"
LoginAction(AnyObject)
}
override func viewDidAppear(_ animated: Bool) {
userName.text = ""
Password.text = ""
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == userName{
Password.becomeFirstResponder()
return true
}
else if textField == Password{
LoginAction(AnyObject.self)
return true
}
return true
}
@IBAction func LoginAction(_ sender: Any) {
if isValidData(username: userName.text!, password: Password.text!){
for u in results {
if userName.text == ((u as! Dictionary<String,AnyObject>)["username"] as! String) && Password.text == ((u as! Dictionary<String,AnyObject>)["password"] as! String){
loggedInUser = "\(userName.text)"
ad.loggedInUserName = userName.text!
loginSuccess = true
}
}
}
if loginSuccess{
print("login Success")
let a = db.selectAll(fromTable: "SELECT email FROM users where username = \"\(ad.loggedInUserName)\"")
if let email = (a?.firstObject as? NSMutableDictionary)?.value(forKey: "email") as? String{
ad.loggedinUserEmail = email
}else{
print("fettching email unsuccessfull")
}
// showWarning(title: “Success”, message: “(loggedInUser!) Logged in successfully”)
performSegue(withIdentifier: “loginToHome”, sender: nil)
//do Something
}
// else{
// showWarning(title: “Error”, message: “Username or Password inco rrect”)
// }
}
@IBAction func SignUpAction(_ sender: Any) {
}
@IBAction func ForgotAction(_ sender: Any) {
}
func isValidData(username : String , password : String) -> Bool {
if username == "" || password == "" {
showWarning(title: "Empty", message: "Please Enter Required Details!! ")
return false
}else if password.characters.count < 8{
showWarning(title: "Error", message: "Password should be of more than 8 characters")
return false
}
return true
}
func showWarning(title : String , message :String) {
alert.title = title
alert.message = message
present(alert, animated: true, completion: nil)
}
// #: -NAV
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
Here Its A Swift File For Sign Up VC…
import UIKit
class SignUpVC: UIViewController,UITextFieldDelegate {
@IBOutlet weak var UserName: UITextField!
@IBOutlet weak var Email: UITextField!
@IBOutlet weak var Password: UITextField!
@IBOutlet weak var PasswordConfirm: UITextField!
var userDefaults = UserDefaults()
var results:Array<Any> = []
var db = Database()
var alert = UIAlertController(title: "Error", message: "Something is not right", preferredStyle: .alert)
var OkAction = UIAlertAction(title: "ok", style: .default, handler: nil)
override func viewDidLoad() {
super.viewDidLoad()
alert.addAction(OkAction)
results = db.selectAll(fromTable: "select * from users") as Array
if !results.isEmpty {
print("got the result from mainvc = \(results)")
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == UserName{
Email.becomeFirstResponder()
return true
}
else if textField == Email{
Password.becomeFirstResponder()
return true
}else if textField == Password{
PasswordConfirm.becomeFirstResponder()
return true
}else if textField == PasswordConfirm{
SignUpAction(AnyObject.self)
return true
}
return true
}
@IBAction func SignUpAction(_ sender: Any) {
let providedEmailAddress = Email.text
let isEmailAddressValid = isValidEmailAddress(emailAddressString: providedEmailAddress!)
if isEmailAddressValid{
print("Email Is Valid.")
//if email is valid then lets check password length
if (Password.text?.characters.count)! > 7 {
// user have entered good 8 or more length password
// fine lets register him
for u in results {
if UserName.text == ((u as! Dictionary<String,AnyObject>)["username"] as! String) || Email.text == ((u as! Dictionary<String,AnyObject>)["email"] as! String){
print("login Success")
//do Something
let alert = UIAlertController(title: "Error", message: "This User already exists Try logging in.", preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(okAction)
present(alert, animated: true, completion: nil)
}}
if Password.text != PasswordConfirm.text{
let alert = UIAlertController(title: "Error", message: "Password does not match", preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(okAction)
present(alert, animated: true, completion: nil)
}else{
let query = "INSERT INTO \"main\".\"users\" (\"username\",\"email\",\"password\") VALUES (\"\(UserName.text! as String)\",\"\(Email.text! as String)\",\"\(Password.text! as String)\")"
let db = Database()
db.fire(query);
}}
} else{
print("Email Address Is Not Valid!!")
//show warning that email invalid
showWarning(title: "Warning", message: "Enter Required Details!!")
}
}
@IBAction func LogInAction(_ sender: Any) {
_ = navigationController?.popToRootViewController(animated: true)
}
func isValidEmailAddress(emailAddressString: String) -> Bool {
var returnValue = true
let emailRegEx = "[A-Z0-9a-z.-_]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,3}"
do {
let regex = try NSRegularExpression(pattern: emailRegEx)
let nsString = emailAddressString as NSString
let results = regex.matches(in: emailAddressString, range: NSRange(location: 0, length: nsString.length))
if results.count == 0
{
returnValue = false
}
} catch let error as NSError {
print("invalid regex: \(error.localizedDescription)")
returnValue = false
}
return returnValue
}
func showWarning(title : String , message :String) {
alert.title = title
alert.message = message
present(alert, animated: true, completion: nil)
}
}
If You Have Some Trouble With Delegate Then Here Add This Two Lines In Your AppDelegate.swift
let ad = UIApplication.shared.delegate as! AppDelegate
let context = ad.persistentContainer.viewContext
Now For Forgot Password VC You Can Use To Reset Password By Getting User Name Or By Getting Email Id Of User… Now Here I It Is The Code For Forgot Password VC.
import UIKit
class forgetpass: UIViewController {
@IBOutlet weak var EmailField: UITextField!
@IBOutlet weak var UserNameField: UITextField!
var db = Database()
var util = Utilities()
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func OkAction(_ sender: UIButton) {
if EmailField.text! != ""{
print("email block")
let b = db.selectAll(fromTable: "SELECT password FROM users where email = \"\(EmailField.text!)\"")
if let pass = (b?.firstObject as? NSMutableDictionary)?.value(forKey: "password") as? String{
print(pass)
let alert = util.configPopup(title: "\(EmailField.text!)", message: "password for \(EmailField.text!) is \(pass)")
present(alert, animated: true, completion: nil)
}else{
print("fettching email unsuccessfull")
let alert = util.configPopup(title: "Oops", message: "\(EmailField.text!) \" email not found")
present(alert, animated: true, completion: nil)
}
}else if UserNameField.text! != ""{
print("username block")
let a = db.selectAll(fromTable: "SELECT password FROM users where username = \"\(UserNameField.text!)\"")
if let pass = (a?.firstObject as? NSMutableDictionary)?.value(forKey: "password") as? String{
print(pass)
let alert = util.configPopup(title: "\(UserNameField.text!)", message: "password for \(UserNameField.text!) is \(pass)")
present(alert, animated: true, completion: nil)
}else{
print("fettching password unsuccessfull")
let alert = util.configPopup(title: "Oops", message: "user not found")
present(alert, animated: true, completion: nil)
}
}
else{
if UserNameField.text!.trimmingCharacters(in: .whitespacesAndNewlines) == "" && EmailField.text!.trimmingCharacters(in: .whitespacesAndNewlines) == "" {
let alert = util.configPopup(title: "please", message: "enter something")
present(alert, animated: true, completion: nil)
}
else{
let alert = util.configPopup(title: "Error", message: "Strange Error")
present(alert, animated: true, completion: nil)
}
print("else block")
}
}
@IBAction func GoBacktoLogin(_ sender: Any) {
self.navigationController?.popToRootViewController(animated: true)
}
}
Create Another Cocoa Touch File For Utilities And Here Is Cde…
import Foundation
class Utilities{
var alert = UIAlertController(title: “Error”, message: “Something is not right”, preferredStyle: .alert)
var OkAction = UIAlertAction(title: “ok”, style: .default, handler: nil)
init() {
alert.addAction(OkAction)
}
func configPopup(title : String , message :String) -> UIAlertController {
alert.title = title
alert.message = message
return alert
}
func stringToDate(date : Date) -> String{
let formatter = DateFormatter()
formatter.setLocalizedDateFormatFromTemplate("yyyy-MM-dd HH:mm")
return formatter.string(from: date)
}
func dateToString(str : String) -> Date{
let formatter = DateFormatter()
formatter.setLocalizedDateFormatFromTemplate("yyyy-MM-dd HH:mm")
return formatter.date(from: str)!
}
}
Any Suggestions…??
Or Any Questions Which You Want To ask Regarding This…!!
All Time Accepted…