Good day. I'm facing a weird issue, I'd like to set the right navigation item to Done in my next when I've selected a row. I tried it, and it's worked. But it's breaking however, because the function which implements the doneEditing body, is only in the next view controller, any help will be really appreciated. This is my code:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "editContact" {
let indexPath = tableView.indexPathForSelectedRow()
let destinationVC: NewCategoryViewController = segue.destinationViewController as! NewCategoryViewController
let contact:Contact = fetchedResultController.objectAtIndexPath(indexPath!) as! Contact
destinationVC.contact = contact
var rightAddBarButtonItem:UIBarButtonItem = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Plain, target: self, action: "doneEditing:")
destinationVC.navigationItem.rightBarButtonItem = rightAddBarButtonItem
}
}
and my next view controller is :
import UIKit
import CoreData
class NewCategoryViewController: UIViewController {
// MARK: - Properties
var contact: Contact? = nil
// initialize the core data context:
let context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
// MARK: - Outlets
#IBOutlet weak var imageHolder: UIImageView!
#IBOutlet weak var nameField: UITextField!
#IBOutlet weak var emailField: UITextField!
#IBOutlet weak var phoneField: UITextField!
#IBOutlet weak var categoryField: UITextField!
// MARK: - Actions
#IBAction func savebtn(sender: AnyObject) {
let entity = NSEntityDescription.entityForName("Contact", inManagedObjectContext: context!)
let newContact = Contact(entity: entity!, insertIntoManagedObjectContext: context)
newContact.name = nameField.text
newContact.email = emailField.text
newContact.phone = phoneField.text
//newContact.photo = UIImageJPEGRepresentation(imageHolder.image, 1)
var error: NSError?
context?.save(&error)
if let errorSaving = error {
var alert = UIAlertController(title: "Alert", message: "Couldn't save contact !!!", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
} else {
nameField.text = ""
emailField.text = ""
phoneField.text = ""
var alert = UIAlertController(title: "Notification", message: "Contact added", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.title = contact?.name
if contact != nil {
nameField.text = contact?.name
emailField.text = contact?.email
phoneField.text = contact?.phone
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func doneEditing() {
}
}
change target from self to destinationVC.
Use this:
var rightAddBarButtonItem:UIBarButtonItem = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Plain, target: destinationVC, action: "doneEditing:")
self should be used when the selector is defined in the same class which makes the call. In this case the selector is in a separate class.
OR
I would suggest you to add the right bar button in the viewDidLoad method of NewCategoryViewController. In which case the code will be:
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Plain, target: self, action: "doneEditing:")
AND
implement doneEditing: method as
func doneEditing(sender: UIBarButtonItem) {
}
Related
I am trying to do something similar to Notes app and I am stuck with what i think is such a stupid thing. When i enter my app there is a add button to add new notes. I can then rename it and enter to a new view controller which consist of only title and textView on the whole screen. I use Codable and UserDefaults to save the data. Title is saving just fine, but whatever i type in textView and then come back to see all rows in tableView and i come back to that particular "note" all my typed text is gone.
This is my didSelectRowAt method
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let vc = storyboard?.instantiateViewController(withIdentifier: "Note") as? NoteViewController {
navigationController?.pushViewController(vc, animated: true)
vc.bodyText = note[indexPath.row].body
vc.titleText = note[indexPath.row].title
if note[indexPath.row].title == "New note" {
let ac = UIAlertController(title: "Rename note", message: "Please enter name for a new note", preferredStyle: .alert)
ac.addTextField()
ac.addAction(UIAlertAction(title: "Cancel", style: .default))
ac.addAction(UIAlertAction(title: "Rename", style: .default) { [unowned self, ac] _ in
let newName = ac.textFields![0]
note[indexPath.row].title = newName.text!
self.tableView.reloadData()
vc.viewDidLoad()
self.save()
})
present(ac, animated: true)
} else {
}
}
}
And my NoteViewController
class NoteViewController: UIViewController, UITextViewDelegate {
#IBOutlet var textView: UITextView!
var bodyText: String?
var titleText: String?
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.rightBarButtonItem = UIBarButtonItem(image: .checkmark, style: .plain, target: self, action: #selector(saveNote))
title = titleText
textView.text = bodyText
}
And Save()
func save() {
let jsonEncoder = JSONEncoder()
if let savedData = try? jsonEncoder.encode(note) {
let defaults = UserDefaults.standard
defaults.set(savedData, forKey: "note")
} else {
print("failed to load data")
}
}
I tried changing my method didSelectRowAt by adding my save() to different places but it's only saving title.
You may use a onSavingTap closure in the NoteViewController to pass the data back to the main view controller.
class NoteViewController: UIViewController, UITextViewDelegate {
var onSavingTap: ((String) -> Void)?
#IBOutlet var textView: UITextView!
var bodyText: String?
var titleText: String?
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.rightBarButtonItem = UIBarButtonItem(image: .checkmark, style: .plain, target: self, action: #selector(saveNote))
title = titleText
textView.text = bodyText
}
#objc func saveNote() {
onSavingTap?(textView.text ?? "")
}
}
then in the didSelectRow method you set the closure to update your data array as follows:
vc.onSavingTap = { [weak self] body in
self?.note[indexPath.row].body = body
self?.save()
}
I am quite puzzled on how will I construct my codes regarding on how I will filter the selected array from a tableviewcell. The JSON below is the content of the tableview which displays like
[
{
"hospitalNumber": "00000001",
"patientName": "Test Patient",
"totalAmount": 1111.3
},
{
"hospitalNumber": "00000002",
"patientName": "Test Patient 2",
"totalAmount": 1312
},
{
"hospitalNumber": "00000003",
"patientName": "Test Patient 3",
"totalAmount": 475
}
]
The problem is how can I display the selected hospitalNumber and patientName in the next View Controller, which will display like
This is what my `PaymentDetailsViewController' have:
var patientList: [Patient]! {
didSet {
latestCreditedAmountTableView.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
getPatientList()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showPatientPaymentDetailsVC" {
if let patientPaymentDetailsVC = segue.destination as? PatientPaymentDetailsViewController {
patientPaymentDetailsVC.isBrowseAll = self.isBrowseAll
if !isBrowseAll {
patientPaymentDetailsVC.patientPayoutDetails = self.selectedPatientPayment
patientPaymentDetailsVC.currentRemittance = self.currentRemittance
patientPaymentDetailsVC.doctorNumber = self.doctorNumber
}
}
}
}
func getPatientList() {
SVProgressHUD.setDefaultMaskType(.black)
SVProgressHUD.show(withStatus: "Retrieving Patient List")
APIService.PatientList.getPatientList(doctorNumber: doctorNumber, periodId: currentRemittance.periodId) { (patientListArray, error) in
guard let patientListPerPayout = patientListArray, error == nil else {
if let networkError = error {
switch networkError {
case .noRecordFound:
let alertController = UIAlertController(title: "No Record Found", message: "You don't have current payment remittance", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default))
self.present(alertController, animated: true, completion: nil)
case .noNetwork:
let alertController = UIAlertController(title: "No Network", message: "\(networkError.rawValue)", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default))
self.present(alertController, animated: true, completion: nil)
default:
let alertController = UIAlertController(title: "Error", message: "There is something went wrong. Please try again", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default))
self.present(alertController, animated: true, completion: nil)
}
}
SVProgressHUD.dismiss()
return
}
self.patientList = patientListPerPayout
self.latestCreditedAmountTableView.reloadData()
SVProgressHUD.dismiss()
return
}
}
**getPerPatientPAyoutDetails(from: String) function**
func getPerPatientPayoutDetails(from: String) {
SVProgressHUD.setDefaultMaskType(.black)
SVProgressHUD.showInfo(withStatus: "Retrieving Patient Details")
APIService.PatientList.getPatientDetailsPerPayout(periodId: currentRemittance.periodId, doctorNumber: doctorNumber, parameterName: .selectedByHospitalNumber, hospitalNumber: from) { (patientPayout, error) in
guard let patientPerPayoutDetails = patientPayout, error == nil else {
if let networkError = error {
switch networkError {
case .noRecordFound:
let alertController = UIAlertController(title: "No Record Found", message: "You don't have current payment remittance", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default))
case .noNetwork:
let alertController = UIAlertController(title: "No Network", message: "\(networkError.rawValue)", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default))
self.present(alertController, animated: true, completion: nil)
default:
let alertController = UIAlertController(title: "Error", message: "There is something went wrong. Please try again", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default))
self.present(alertController, animated: true, completion: nil)
}
}
SVProgressHUD.dismiss()
return
}
self.selectedPatientPayment = patientPerPayoutDetails
print(self.selectedPatientPayment)
SVProgressHUD.dismiss()
return
}
}
Base on the gePatientList() function, it will just pull the full list of the patients. I don't know how I will pass the data of the selected patient to another VC. Hope you can help me. Thank you so much.
Codes that might help to understand the flow of my codes
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch indexPath.section {
case 0: break
case 1: let selectedpatient = patientList[indexPath.row].hospitalNumber
print(selectedpatient!)
self.isBrowseAll = false
getPerPatientPayoutDetails(from: selectedpatient!)
default: break
}
}
Below is the another View Controller that will display the patientName and hospitalNumber
PatientPaymentDetailsVC
class PatientPaymentDetailsViewController: UIViewController {
#IBOutlet weak var patientProcedureTableView: UITableView!
#IBOutlet weak var hospitalNumberLabel: UILabel!
#IBOutlet weak var patientNameLabel: UILabel!
var currentRemittance: CurrentRemittance!
var doctorNumber: String!
var isBrowseAll: Bool!
var patientList: [Patient]!
var patientPayoutDetails: [PatientPayoutDetails]!
override func viewDidLoad() {
super.viewDidLoad()
setupPatientInfo()
}
//MARK: FUNCTION
func setupPatientInfo() {
self.patientNameLabel.text = patient.patientName
self.hospitalNumberLabel.text = patient.hospitalNumber
}
The pulled data under the getPerPatientPayoutDetails function from the didselect will be displayed in PatientPaymentDetailsVC. Below is the output, as you can I see I can pull the data under getPerPatientPayoutDetails but the patientName and hospitalNumber does not display the data.
First of all don't get the data from the table view cell, get it from the data source
Connect the segue to the cell.
Delete the entire method didSelectRowAt
When prepare(for segue is called the sender parameter is the cell.
Get the index path from the cell and get the patient at that index path.
Rather than passing multiple parameters declare a var patient : Patient! property in the destination controller and hand over the patient instance.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard segue.identifier == "showPatientPaymentDetailsVC",
let cell = sender as? UITableViewCell,
let indexPath = tableView.indexPath(for: cell) else { return }
let patient = patientList[indexPath.row]
getPerPatientPayoutDetails(from: patient.hospitalNumber)
let patientPaymentDetailsVC = segue.destination as! PatientPaymentDetailsViewController
patientPaymentDetailsVC.patient = patient
patientPaymentDetailsVC.patientPayoutDetails = self.selectedPatientPayment
patientPaymentDetailsVC.currentRemittance = self.currentRemittance
patientPaymentDetailsVC.doctorNumber = self.doctorNumber
}
class PatientPaymentDetailsViewController: UIViewController {
#IBOutlet weak var patientProcedureTableView: UITableView!
#IBOutlet weak var hospitalNumberLabel: UILabel!
#IBOutlet weak var patientNameLabel: UILabel!
var currentRemittance: CurrentRemittance!
var doctorNumber = ""
var isBrowseAll = false
var patient : Patient!
var patientPayoutDetails: [PatientPayoutDetails]!
override func viewDidLoad() {
super.viewDidLoad()
setupPatientInfo()
}
//MARK: FUNCTION
func setupPatientInfo() {
self.patientNameLabel.text = patient.patientName
self.hospitalNumberLabel.text = patient.hospitalNumber
}
Side note:
Don't declare patientList as implicit unwrapped optional, declare it as non-optional empty array
var patientList : [Patient]()
Use tableView(_:didSelectRowAt:) method by conforming to UITableViewDelegate.
Get the selected patient as displayed below:
selectedPatient = tableView[indexpath.row] as! [String:Any]
As per your edited question, try this:
let patient = patientList[indexPath.row] as! Patient
I know that Mobile Hub provides a built in auth UI that handles the sign in and registration process. But I want to use my own storyboard and process the input fields in it to login and register users.
Here's what I have tried for login:
class LoginVC: UIViewController {
#IBOutlet weak var loginButton: UIButton!
#IBOutlet weak var forgotPasswordLabel: UILabel!
#IBOutlet weak var signUpLabel: UILabel!
#IBOutlet weak var emailTF: UITextField!
#IBOutlet weak var passwordTF: UITextField!
var passwordAuthenticationCompletion: AWSTaskCompletionSource<AWSCognitoIdentityPasswordAuthenticationDetails>!
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.tintColor = UIColor.white
self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
self.navigationController!.navigationBar.setBackgroundImage(UIImage(), for: .default)
self.navigationController!.navigationBar.shadowImage = UIImage()
self.navigationController!.navigationBar.isTranslucent = true
loginButton.addTarget(self, action: #selector(loginUser), for: .touchUpInside)
loginButton.layer.cornerRadius = 18
emailTF.addPadding(.left(35))
passwordTF.addPadding(.left(35))
let tap = UITapGestureRecognizer(target: self, action: #selector(goToForgotPasswordVC))
let tap2 = UITapGestureRecognizer(target: self, action: #selector(goToSignUp1VC))
forgotPasswordLabel.isUserInteractionEnabled = true
forgotPasswordLabel.addGestureRecognizer(tap)
signUpLabel.isUserInteractionEnabled = true
signUpLabel.addGestureRecognizer(tap2)
AWSCognitoUserPoolsSignInProvider.sharedInstance().setInteractiveAuthDelegate(self)
}
func getDetails(_ authenticationInput: AWSCognitoIdentityPasswordAuthenticationInput, passwordAuthenticationCompletionSource: AWSTaskCompletionSource<AWSCognitoIdentityPasswordAuthenticationDetails>) {
passwordAuthenticationCompletion = passwordAuthenticationCompletionSource
}
func didCompleteStepWithError(_ error: Error?) {
if error != nil {
let alertController = UIAlertController(title: error?.localizedDescription, message: "error", preferredStyle: UIAlertControllerStyle.alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default, handler: nil))
self.present(alertController, animated: true, completion: nil)
} else {
print("logged in")
}
}
#objc func loginUser() {
let email = emailTF.text?.trimmingCharacters(in: .whitespacesAndNewlines)
let password = passwordTF.text?.trimmingCharacters(in: .whitespacesAndNewlines)
passwordAuthenticationCompletion.set(result: AWSCognitoIdentityPasswordAuthenticationDetails.init(username: email!, password: password!))
}
But passwordAuthenticationCompletion.set returns nil for me. What am I missing?
Any help is appreciated.
Thanks
In an app I am currently writing, I have a string named 'User' which stores the user's name for a game. The value of the string, when printed anywhere else in the Swift file, prints the value that I have set, as an optional.
If I try to use this string as the title of an action sheet action, the string is automatically set to nil, which I can see as both the title of the action and which is printed when I ask it to print(user).
If anyone could shed some light as to why this is happening, or how to prevent it, that would be great. I have also posted my Swift file below, thanks.
import UIKit
class MainViewController: UIViewController {
#IBOutlet weak var segmentedControl: UISegmentedControl!
#IBOutlet weak var firstView: UIView!
#IBOutlet weak var secondView: UIView!
var user:String!
var playerTwo:String!
var playerThree:String!
var playerFour:String!
var playerFive:String!
var playerSix:String!
var userCards = [String]()
override func viewDidLoad() {
super.viewDidLoad()
firstView?.isHidden = false
secondView?.isHidden = true
}
#IBAction func valueDidChange(_ sender: UISegmentedControl) {
switch segmentedControl.selectedSegmentIndex {
case 0:
firstView.isHidden = false
secondView.isHidden = true
case 1:
firstView.isHidden = true
secondView.isHidden = false
default:
break;
}
}
#IBAction func confirm(_ sender: UIButton) {
let alertController = UIAlertController(title: "Action Sheet", message: "What would you like to do?", preferredStyle: .actionSheet)
let userButton = UIAlertAction(title: user /* Here I have tried with putting both 'user', and "\(user)"*/, style: .default, handler: { (action) -> Void in
print("User button tapped")
})
let deleteButton = UIAlertAction(title: "Delete button test", style: .destructive, handler: { (action) -> Void in
print("Delete button tapped")
})
let cancelButton = UIAlertAction(title: "Cancel", style: .cancel, handler: { (action) -> Void in
print("Cancel button tapped")
})
alertController.addAction(userButton)
alertController.addAction(deleteButton)
alertController.addAction(cancelButton)
self.present(alertController, animated: true, completion: nil)
}
}
The value is passed into the above file directly from this code in another file:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showMainController" {
let VC = segue.destination as! MainViewController
VC.user = self.user
if playerTwo != nil {
VC.playerTwo = self.playerTwo
}
if playerThree != nil {
VC.playerThree = self.playerThree
}
if playerFour != nil {
VC.playerFour = self.playerFour
}
if playerFive != nil {
VC.playerFive = self.playerFive
}
if playerSix != nil {
VC.playerSix = self.playerSix
}
}
}
The value is, however, passed through several view controllers, and is initially set here:
if (meTextField.text?.isEmpty)! == false {
let p1 = meTextField.text!
initialPlayersDict["player1"] = "\(p1)"
if errLabelNotBlank {
errorLabel.text = ""
errLabelNotBlank = false
}
}
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)
}
}
}