Segue to next view controller after successful sign up - ios

I've searched and searched and searched but not found a solution. The sign up works but will not segue to the next view controller. Heres my code:
import UIKit
import Parse
import Bolts
class SignUpVC: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet weak var profilePictureIV: UIImageView!
#IBOutlet weak var firstNameTF: UITextField!
#IBOutlet weak var lastNameTF: UITextField!
#IBOutlet weak var newUsernameTF: UITextField!
#IBOutlet weak var newPasswordTF: UITextField!
#IBOutlet weak var emailTF: UITextField!
#IBOutlet weak var phoneNumberTF: UITextField!
#IBAction func setProfilePicture(sender: AnyObject) {
let myPickerController = UIImagePickerController()
myPickerController.delegate = self
myPickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
self.presentViewController(myPickerController, animated: true, completion: nil)
}
#IBAction func signUpButton(sender: AnyObject) {
let spinner: UIActivityIndicatorView = UIActivityIndicatorView(frame: CGRectMake(0, 0, 150, 150)) as UIActivityIndicatorView
if firstNameTF.text != "" && lastNameTF.text != "" && newUsernameTF.text != "" && newPasswordTF.text != "" && emailTF.text != "" && phoneNumberTF.text != "" {
let newUser = PFUser()
if let profilePictureImage = profilePictureIV?.image {
let profilePicture = UIImageJPEGRepresentation(profilePictureImage, 1)!
let profilePictureImageFile = PFFile(data: profilePicture)
newUser["profilePicture"] = profilePictureImageFile
}
newUser["firstName"] = firstNameTF.text
newUser["lastName"] = lastNameTF.text
newUser.username = newUsernameTF.text
newUser.password = newPasswordTF.text
newUser.email = emailTF.text
newUser["phoneNumber"] = phoneNumberTF.text
newUser.signUpInBackgroundWithBlock {
(succeeded: Bool, error: NSError?) -> Void in
if let error = error {
spinner.startAnimating()
self.alert("Opps", textMessage: (error.localizedDescription))
} else {
spinner.startAnimating()
self.alert("Congratualtion!", textMessage: "Success, your account has been created.")
self.performSegueWithIdentifier("showMessages", sender: self)
}
}
} else {
alert("Hmm...", textMessage: "If you want an account, please fill in the blanks.")
}
}
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.
}
override func viewWillAppear(animated: Bool) {
self.navigationController!.navigationBar.hidden = false
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
profilePictureIV.image = info[UIImagePickerControllerOriginalImage] as? UIImage
self.dismissViewControllerAnimated(true, completion: nil)
}
func alert(textTitle: String, textMessage: String) {
let alertController = UIAlertController(title: textTitle, message: textMessage, preferredStyle: .Alert)
alertController.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
self.presentViewController(alertController, 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 i play the self.performSegueWithIdentifier("showMessages", sender: self) line anywhere else then when i run the program and press the signup button it will directly go to in the messages view controller without any signup required.

as Paulw11 said , Try to remove alert message :-
if let error = error {
spinner.startAnimating()
self.alert("Opps", textMessage: (error.localizedDescription))
} else {
spinner.startAnimating()
self.performSegueWithIdentifier("showMessages", sender: self)
}
or You can call the handler in your code.
if let error = error {
spinner.startAnimating()
self.alert("Opps", textMessage: (error.localizedDescription))
} else {
spinner.startAnimating()
var alert = UIAlertController(title: "Welcome", message: "Login", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title:"OK", style: .Default, handler: { action in self.performSegueWithIdentifier("showMessages", sender: self) }
}

You can not pass self as a argument in side the block.
so create a method to call a segue
#IBAction func signUpButton(sender: AnyObject) {
let spinner: UIActivityIndicatorView = UIActivityIndicatorView(frame: CGRectMake(0, 0, 150, 150)) as UIActivityIndicatorView
if firstNameTF.text != "" && lastNameTF.text != "" && newUsernameTF.text != "" && newPasswordTF.text != "" && emailTF.text != "" && phoneNumberTF.text != "" {
let newUser = PFUser()
if let profilePictureImage = profilePictureIV?.image {
let profilePicture = UIImageJPEGRepresentation(profilePictureImage, 1)!
let profilePictureImageFile = PFFile(data: profilePicture)
newUser["profilePicture"] = profilePictureImageFile
}
newUser["firstName"] = firstNameTF.text
newUser["lastName"] = lastNameTF.text
newUser.username = newUsernameTF.text
newUser.password = newPasswordTF.text
newUser.email = emailTF.text
newUser["phoneNumber"] = phoneNumberTF.text
newUser.signUpInBackgroundWithBlock {
(succeeded: Bool, error: NSError?) -> Void in
if let error = error {
spinner.startAnimating()
self.alert("Opps", textMessage: (error.localizedDescription))
} else {
spinner.startAnimating()
self.alert("Congratualtion!", textMessage: "Success, your account has been created.")
callSegue()
}
}
} else {
alert("Hmm...", textMessage: "If you want an account, please fill in the blanks.")
}
}
func callSegue()
{
self.performSegueWithIdentifier("showMessages", sender: self)
}

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

Profile page swift 3 errors

This is the code that I have created for my profile page but it has some mistakes that i would like to adjust.
import UIKit
import FirebaseStorage
import FirebaseDatabase
import FirebaseAuth
import Firebase
class ProfileClass: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet weak var userImagePicker: RoundButton!
#IBOutlet weak var ProfilePicture: RoundImage!
#IBOutlet weak var usernameField: UITextField!
#IBOutlet weak var imageLoader: UIActivityIndicatorView!
var loggedInUser = AnyObject?()
var databaseRef = FIRDatabase.database().reference()
var storageRef = FIRStorage.storage().reference()
var imagePicker = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
self.loggedInUser = FIRAuth.auth()?.currentUser
self.databaseRef.child("user_profile").child(self.loggedInUser!.uid).observeSingleEvent(of: FIRDataEventType(.Value) { (snapshot:FIRDataSnapshot) in
if(snapshot.value!["usernameField"] !== nil) {
self.usernameField.text = snapshot.value!["usernameField"] as? String
}
if(snapshot.value!["profile_pic"] !== nil) {
let databaseProfilePic = snapshot.value!["profile_pic"]
as! String
let data = NSData(contentsOfURL: NSURL(string: databaseProfilePic)!)
self.setProfilePicture(self.ProfilePicture,imageToSet:UIImage(data:data!)!)
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func logoutTapped(_ sender: Any) {
let firebaseAuth = FIRAuth.auth()
do {
try firebaseAuth?.signOut()
} catch let signOutError as NSError {
print ("Error signing out: %#", signOutError)
}
self.performSegue(withIdentifier: "goToLogin", sender: self)
}
#IBAction func TapProfileButton(_ sender: RoundButton) {
let myActionShett = UIAlertController(title:"Profile Picture",message:"Select",preferredStyle: UIAlertControllerStyle.actionSheet)
let viewPicture = UIAlertAction(title: "View Picture", style: UIAlertActionStyle.default) { (action) in
let imageView = sender.view as! RoundImage
let newImageView = RoundImage(image: imageView.image)
newImageView.frame = self.view.frame
newImageView.backgroundColor = UIColor.blackColor()
newImageView.contentMode = .scaleAspectFit
newImageView.userInteractionEnabled = true
let tap = UITapGestureRecognizer(target:self,action:#selector(self.dismissFullScreenImage))
newImageView.addGestureRecognizer(tap)
self.view.addSubview(newImageView)
}
let photoGallery = UIAlertAction(title: "Photos", style: UIAlertActionStyle.default) { (action) in
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.savedPhotosAlbum)
{
self.imagePicker.delegate = self
self.imagePicker.sourceType = UIImagePickerControllerSourceType.savedPhotosAlbum
self.imagePicker.allowsEditing = true
self.present(self.imagePicker, animated: true, completion: nil)
}
}
let camera = UIAlertAction(title: "Camera", style: UIAlertActionStyle.default)
{ (action) in
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera)
{
self.imagePicker.delegate = self
self.imagePicker.sourceType = UIImagePickerControllerSourceType.camera
self.imagePicker.allowsEditing = true
self.present(self.imagePicker, animated: true, completion: nil)
}
}
myActionShett.addAction(viewPicture)
myActionShett.addAction(photoGallery)
myActionShett.addAction(camera)
myActionShett.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: nil))
self.present(myActionShett, animated: true, completion: nil)
}
func dismissFullScreenImage(sender:UITapGestureRecognizer)
{
sender.view?.removeFromSuperview()
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
self.imageLoader.stopAnimating()
setProfilePicture(self.ProfilePicture,imageToSet: image)
if let imageData: NSData = UIImagePNGRepresentation(self.ProfilePicture, image!)!
{
let profilePicStorageRef = storageRef.child("user_profiles/\(self.loggedInUser!.uid)/profile_pic")
let uploadTask = profilePicStorageRef.putData(imageData, metadata: nil)
{metadata,error in
if(error == nil)
{
let downloadUrl = metadata!.downloadUrl()
self.databaseRef.child("user_profile").child(self.loggedInUser!.uid).child("profile_pic").setValue(downloadUrl!.absoluteString)
}
else
{
print(error?.localizedDescription)
}
self.imageLoader.stopAnimating()
}
}
self.dismiss(animated: true, completion: nil)
}
}
You have to give proper type. You can not initialize object of type AnyObject. and Obviously with not using AnyObject?.

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
}

fatal error: unexpectedly found nil while unwrapping an Optional value Parse sign up

I'm trying to do a signup page but for some reason I keep getting the same error "fatal error: unexpectedly found nil while unwrapping an Optional value" on the line "let username = self.usernameField.text" when I test it out in the simulator. I know the error has something to do with a value being nil but cant figure out how to fix it please help :(
Code =
#IBOutlet weak var emailField: UITextField?
#IBOutlet weak var usernameField: UITextField?
#IBOutlet weak var passwordField: 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 signUpAction(sender: AnyObject) {
let username = self.usernameField!.text
let password = self.passwordField!.text
let email = self.emailField!.text
let finalEmail = email!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
// Validate the text fields
if username?.characters.count < 5 {
let alert = UIAlertView(title: "Invalid", message: "Username must be greater than 5 characters", delegate: self, cancelButtonTitle: "OK")
alert.show()
} else if password?.characters.count < 8 {
let alert = UIAlertView(title: "Invalid", message: "Password must be greater than 8 characters", delegate: self, cancelButtonTitle: "OK")
alert.show()
} else if email?.characters.count < 8 {
let alert = UIAlertView(title: "Invalid", message: "Please enter a valid email address", delegate: self, cancelButtonTitle: "OK")
alert.show()
} else {
// Run a spinner to show a task in progress
let spinner: UIActivityIndicatorView = UIActivityIndicatorView(frame: CGRectMake(0, 0, 150, 150)) as UIActivityIndicatorView
spinner.startAnimating()
let newUser = PFUser()
newUser.username = username
newUser.password = password
newUser.email = finalEmail
// Sign up the user asynchronously
newUser.signUpInBackgroundWithBlock({ (succeed, error) -> Void in
// Stop the spinner
spinner.stopAnimating()
if ((error) != nil) {
let alert = UIAlertView(title: "Error", message: "\(error)", delegate: self, cancelButtonTitle: "OK")
alert.show()
} else {
let alert = UIAlertView(title: "Success", message: "Signed Up", delegate: self, cancelButtonTitle: "OK")
alert.show()
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let viewController:UIViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("Home")
self.presentViewController(viewController, animated: true, completion: nil)
})
}
})
Try this...
import Foundation
import Parse
import UIKit
class LoginViewController: UIViewController {
#IBOutlet weak var userNameTF: UITextField!
#IBOutlet weak var passWordTF: UITextField!
#IBOutlet weak var emailTF: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func SignUp(sender: AnyObject) {
signUp()
}
#IBAction func Login(sender: AnyObject) {
login()
}
func signUp() {
let user = PFUser()
user.username = userNameTF.text
user.password = passWordTF.text
user.email = emailTF.text
// other fields can be set if you want to save more information
// user["phone"] = "650-555-0000"
user.signUpInBackgroundWithBlock { (success: Bool, error: NSError?) -> Void in
if error == nil {
print("Sign Up Succesful")
} else {
print("Sign Up Failed")
}
}
}
func login() {
let user = PFUser()
user.username = userNameTF.text
user.password = passWordTF.text
PFUser.logInWithUsernameInBackground(userNameTF.text!, password: passWordTF.text!, block: {
(user: PFUser?, Error: NSError?) -> Void in
if Error == nil {
dispatch_async(dispatch_get_main_queue()) {
var Storyboard = UIStoryboard(name: "Main", bundle: nil)
var AfterLoginVC: UIViewController = Storyboard.instantiateViewControllerWithIdentifier("AfterLoginVC") as! UINavigationController
self.presentViewController(AfterLoginVC, animated: true, completion: nil)
}
} else {
print("Login Error, check credentials")
}
})
}
}
"AterLoginVC" is the storyboard identifier of the view controller that you want to instantiate after a successful attempt at login. From this you can then add you if/else statements to evaluate conditions and return the error to the user accordingly

codes are not dismissing keyboard

I added resignFirstResponder and touchesBegan to my code but the keyboard is not dismissing. I already checked the delegate and assigned delegate to textfields but still no sign of dismissing.
Please help spot the error? (i'm guessing it might be about multiple textFields?)
import UIKit
import Parse
class SignUpViewController: UIViewController, UITextFieldDelegate {
#IBAction func BackToFirstPageButton(sender: AnyObject) {
performSegueWithIdentifier("BackToLogInPage", sender: self)
}
func SignOutForEmailVerification() {
PFUser.logOut()
performSegueWithIdentifier("BackToLogInPage", sender: self)
}
#IBOutlet var UsernameTextField: UITextField!
#IBOutlet var PasswordTextField: UITextField!
#IBOutlet var EmailTextField: UITextField!
var ActivityIndicator:UIActivityIndicatorView = UIActivityIndicatorView()
#IBAction func SignUpButton(sender: AnyObject) {
if UsernameTextField.text == "" || PasswordTextField.text == "" || EmailTextField.text == "" {
let SignUpAlert = UIAlertController (title: "Error in form", message: "Please fill in the blanks", preferredStyle: UIAlertControllerStyle.Alert)
SignUpAlert.addAction((UIAlertAction(title: "Dismiss", style: .Default, handler: { (action) -> Void in
})))
self.presentViewController(SignUpAlert, animated: true, completion: nil)
} else {
ActivityIndicator = UIActivityIndicatorView(frame: CGRectMake(0, 0, 50, 50))
ActivityIndicator.center = self.view.center
ActivityIndicator.hidesWhenStopped = true
ActivityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray
view.addSubview(ActivityIndicator)
ActivityIndicator.startAnimating()
UIApplication.sharedApplication().beginIgnoringInteractionEvents()
var user = PFUser()
user.username = UsernameTextField.text
user.password = PasswordTextField.text
user.email = EmailTextField.text
user.signUpInBackgroundWithBlock({ (success, error) -> Void in
self.ActivityIndicator.stopAnimating()
UIApplication.sharedApplication().endIgnoringInteractionEvents()
if error == nil {
let EmailVerificationAlert = UIAlertController(title: "Email Verification", message: "Please click the link in an email we have just sent you", preferredStyle: UIAlertControllerStyle.Alert)
EmailVerificationAlert.addAction(UIAlertAction(title: "Okay", style: .Default, handler: { EmailVerificationAlert in self.SignOutForEmailVerification()})
)
self.presentViewController(EmailVerificationAlert, animated: true, completion: nil)
}
})
}
func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.UsernameTextField.delegate = self
self.PasswordTextField.delegate = self
self.EmailTextField.delegate = self
}
func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
}
func textFieldShouldReturn(textField: UITextField!) -> Bool {
textField.resignFirstResponder()
return true
}
}
}
When user taps "Return" key on the keyboard
As you already added the UITextFieldDelegate, try modifying this code :
func textFieldShouldReturn(textField: UITextField!) -> Bool {
self.UsernameTextField.resignFirstResponder();
self.EmailTextField.resignFirstResponder();
self.PasswordTextField.resignFirstResponder();
return true;
}
This will work when the user taps the button return on the keyboard.
Your mistake is as you said handling multiple text fields. Also you have to say which one you want to resignFirstResponder().
When user taps screen
User could also dismiss the keyboard by tapping anywhere on the screen.
Here we have a UITapGestureRecognizer that detects the tap to dismiss keyboard. It is an alternative solution.
override func viewDidLoad() {
super.viewDidLoad()
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboard")
view.addGestureRecognizer(tap)
}
func dismissKeyboard() {
view.endEditing(true)
}
import UIKit
import Parse
class SignUpViewController: UIViewController, UITextFieldDelegate {
#IBOutlet var UsernameTextField: UITextField!
#IBOutlet var PasswordTextField: UITextField!
#IBOutlet var EmailTextField: UITextField!
var ActivityIndicator:UIActivityIndicatorView = UIActivityIndicatorView()
var currentTextField : UITextField?
func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.UsernameTextField.delegate = self
self.PasswordTextField.delegate = self
self.EmailTextField.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func BackToFirstPageButton(sender: AnyObject) {
performSegueWithIdentifier("BackToLogInPage", sender: self)
}
func SignOutForEmailVerification() {
PFUser.logOut()
performSegueWithIdentifier("BackToLogInPage", sender: self)
}
#IBAction func SignUpButton(sender: AnyObject) {
if UsernameTextField.text == "" || PasswordTextField.text == "" || EmailTextField.text == "" {
let SignUpAlert = UIAlertController (title: "Error in form", message: "Please fill in the blanks", preferredStyle: UIAlertControllerStyle.Alert)
SignUpAlert.addAction((UIAlertAction(title: "Dismiss", style: .Default, handler: { (action) -> Void in
})))
self.presentViewController(SignUpAlert, animated: true, completion: nil)
} else {
currentTextField?.resignFirstResponder();
ActivityIndicator = UIActivityIndicatorView(frame: CGRectMake(0, 0, 50, 50))
ActivityIndicator.center = self.view.center
ActivityIndicator.hidesWhenStopped = true
ActivityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray
view.addSubview(ActivityIndicator)
ActivityIndicator.startAnimating()
UIApplication.sharedApplication().beginIgnoringInteractionEvents()
var user = PFUser()
user.username = UsernameTextField.text
user.password = PasswordTextField.text
user.email = EmailTextField.text
user.signUpInBackgroundWithBlock({ (success, error) -> Void in
self.ActivityIndicator.stopAnimating()
UIApplication.sharedApplication().endIgnoringInteractionEvents()
if error == nil {
let EmailVerificationAlert = UIAlertController(title: "Email Verification", message: "Please click the link in an email we have just sent you", preferredStyle: UIAlertControllerStyle.Alert)
EmailVerificationAlert.addAction(UIAlertAction(title: "Okay", style: .Default, handler: { EmailVerificationAlert in self.SignOutForEmailVerification()})
)
self.presentViewController(EmailVerificationAlert, animated: true, completion: nil)
}
})
}
func textFieldDidBeginEditing(textField: UITextField!){
currentTextField = textField;
}
func textFieldShouldReturn(textField: UITextField!) -> Bool {
currentTextField.resignFirstResponder()
return true
}
}
}

Resources