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

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
}
}

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

terminating with uncaught exception of type NSException when trying to do an UIAlert or a performSegueWithIdentifier

When I run my app the output says:
terminating with uncaught exception of type NSException
when I try to do an performseguewithidentifier or a UIAlert. I am parsing my json data but when I try to either do a UIAlert or a segue when that data equals something I get this error. What am I doing wrong?
import UIKit
class registerViewController: UIViewController {
#IBOutlet weak var nameInput: UITextField!
#IBOutlet weak var emailInput: UITextField!
#IBOutlet weak var passwordInput: UITextField!
#IBOutlet weak var confirmPassInput: UITextField!
var errorGot = String()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
print(self.errorGot)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func sendBtn(_ sender: UIButton) {
let name = nameInput.text
let email = emailInput.text
let password = passwordInput.text
let confirmPass = confirmPassInput.text
if(name?.isEmpty == true || email?.isEmpty == true || password?.isEmpty == true || confirmPass?.isEmpty == true){
errorMessage(msg: "Alla fält måste vara infyllda!", type: "error")
}else if(password != confirmPass){
errorMessage(msg: "Dina lösenord stämmer ej överens", type: "error")
}else{
let myUrl = URL(string: "http://mywebsitething.com/wasterace/app/storeData/registration.php?email=\(email!)&name=\(name!)&password=\(password!)")
var request = URLRequest(url:myUrl!)
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request as URLRequest) {data,response,error in
if(error != nil){
print("error")
}
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [Any]
for jsonResult in json {
let jsonDict = jsonResult as! [String:String]
let error = jsonDict["error"]!
self.printFunc(msg: error)
}
} catch {
print("errorcath")
}
}
task.resume()
}
}
func printFunc(msg: String){
if(msg == "true"){
self.errorMessage(msg: "Invalid entry", type: "error")
}else if (msg == "false"){
self.errorMessage(msg: "You have now registered", type: "success")
}
}
func errorMessage(msg: String, type: String){
if(type == "error"){
let alert = UIAlertController(title: "Error", message: msg, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}else if (type == "success"){
let alert = UIAlertController(title: "Grattis!", message: msg, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Logga In", style: UIAlertActionStyle.default, handler: { action in
self.performSegue(withIdentifier: "toLoginRegister", sender: self)
}))
self.present(alert, animated: true, completion: nil)
}
}
}
I had the same issue and my problem solved by using :
DispatchQueue.main.async { [weak self] in
}
I mean try to put your alert in this block.
// Hope this helps you some how.

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
}

swift 2.1 table view controller segue to view delegate errors with unexpectedly found nil

Ive research this and i'm pretty sure this is the correct way but I keep getting
fatal error: unexpectedly found nil while unwrapping an Optional value
on the prepareForSegue line
selectSingleVC!.delegate = self
The relevant bits of code are here. I'm not sure why the nil is there and its driving me mad :-)
class FriendsChatViewController: UITableViewController, UIActionSheetDelegate, SelectSingleViewControllerDelegate, SelectMultipleViewControllerDelegate {
...
#IBAction func compose(sender: UIBarButtonItem) {
weak var wself: FriendsChatViewController? = self
let action = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) { _ in
}
let singleAction = UIAlertAction(title: "Single recipient", style: UIAlertActionStyle.Default) { _ in
if let _ = wself {
self.performSegueWithIdentifier("selectSingleSegue", sender: self)
}
}
let multipleAction = UIAlertAction(title: "Multiple recipients", style: UIAlertActionStyle.Default) { _ in
if let _ = wself {
self.performSegueWithIdentifier("selectMultipleSegue", sender: self)
}
}
action.addAction(cancelAction)
action.addAction(singleAction)
action.addAction(multipleAction)
self.presentViewController(action, animated: true, completion: nil)
}
...
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "messagesChatSegue" {
let chatVC = segue.destinationViewController as! ChatViewController
//chatVC.hidesBottomBarWhenPushed = true
let groupId = sender as! String
chatVC.groupId = groupId
} else if segue.identifier == "selectSingleSegue" {
let selectSingleVC = segue.destinationViewController as? SelectSingleViewController
print(self)
selectSingleVC!.delegate = self <-- ERROR is here
} else if segue.identifier == "selectMultipleSegue" {
let selectMultipleVC = segue.destinationViewController as? SelectMultipleViewController
selectMultipleVC!.delegate = self
}
}
This is relevant sections of my SelectSingleViewController
protocol SelectSingleViewControllerDelegate {
func didSelectSingleUser(user: PFUser)
}
class SelectSingleViewController: UITableViewController, UISearchBarDelegate {
var friends = [PFObject]()
var user = PFUser()
var delegate: SelectSingleViewControllerDelegate!
...
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
self.dismissViewControllerAnimated(true, completion: { () -> Void in
if self.delegate != nil {
let friendObject = self.friends[indexPath.row]
let friend = friendObject["user"] as! PFUser
self.user = friend
print(self.user)
self.delegate.didSelectSingleUser(self.user)
}
})
}
Ive been racking my brain on this for hours and need some assistance in my error. Thanks
Put a check on selectSingleVC. Its crashing because selectSingleVC is nil and you are being sure it of type SelectSingleViewController and trying to use force unwrapping ! operation.
My guess is the segue with identifier selectSingleSegue is not linked to SelectSingleViewController in story board. Please double check your connections.
as mentioned by #dan my segue.destinationViewController was equal to UINavigationViewController and because of changes in Swift 2
let selectSingleVC = segue.destinationViewController.topViewController as? SelectSingleViewController
will no longer work. My revised code is
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "messagesChatSegue" {
let chatVC = (segue.destinationViewController as! UINavigationController).topViewController as! ChatViewController
//chatVC.hidesBottomBarWhenPushed = true
let groupId = sender as! String
chatVC.groupId = groupId
} else if segue.identifier == "selectSingleSegue" {
let selectSingleVC = (segue.destinationViewController as! UINavigationController).topViewController as! SelectSingleViewController
print(segue.destinationViewController)
selectSingleVC.delegate = self
} else if segue.identifier == "selectMultipleSegue" {
let selectMultipleVC = (segue.destinationViewController as! UINavigationController).topViewController as!SelectMultipleViewController
selectMultipleVC.delegate = self
}
}

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