Attempting to create a Firebase login/signup but no matter what I enter into the email textfield it prints the error "The email address is badly formatted", even if its a valid email. Also I'm a beginner so...sorry about the format. This is the code:
import UIKit
import Firebase
import FirebaseAuth
class SecondViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// FirebaseApp.configure()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBOutlet weak var username_input: UITextField!
#IBOutlet weak var password_input: UITextField!
#IBOutlet weak var signupButton: UIButton!
#IBOutlet weak var segmentControl: UISegmentedControl!
#IBAction func doSignUp(_ sender: Any) {
let email = self.username_input.text
let password = self.password_input.text
if email != "" && password != ""
{
if segmentControl.selectedSegmentIndex == 1 //signup
{
Auth.auth().createUser(withEmail: email!, password: password!, completion: { (user, error) in
if error == nil {
print("You have successfully signed up")
// Goes to main page
let vc = self.storyboard?.instantiateViewController(withIdentifier: "Home")
self.present(vc!, animated: true, completion: nil)
self.performSegue(withIdentifier: "segue", sender: self)
let request = Auth.auth().currentUser?.createProfileChangeRequest()
request?.displayName = email
}
else {
if (error?.localizedDescription) != nil
{
// let alertController = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: .alert)
// let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
// alertController.addAction(defaultAction)
// self.present(alertController, animated: true, completion: nil)
print(error?.localizedDescription as Any)
let myError1 = error?.localizedDescription
print(myError1!)
}
}
})
}
}
if segmentControl.selectedSegmentIndex == 0 {
//login
Auth.auth().signIn(withEmail: self.username_input.text!, password: self.password_input.text!, completion: { (user, error) in
if user != nil
{
self.performSegue(withIdentifier: "segue", sender: self)
//sign in user
}
else
{
if (error?.localizedDescription) != nil
{
_ = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: .alert)
let myError = error?.localizedDescription
print(myError!)
}
else {
Auth.auth().signIn(withEmail: self.username_input.text!, password: self.password_input.text!, completion: { (user, error) in
if user != nil
{
self.performSegue(withIdentifier: "segue", sender: self)
//sign in user
}
else
{
if (error?.localizedDescription) != nil
{
_ = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: .alert)
let myError = error?.localizedDescription
print(myError!)
}
}
}
)}
}
}
)
}
}
My code For Reference have a look
//Outlets
#IBOutlet weak var emailTextField: UITextField!
#IBOutlet weak var passwordTextField: UITextField!
//Sign Up Action for email
#IBAction func createAccountAction(_ sender: AnyObject) {
let email = emailTextField.text
let pass = passwordTextField.text
if emailTextField.text == "" {
let alertController = UIAlertController(title: "Error", message: "Please enter your email and password", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
present(alertController, animated: true, completion: nil)
} else {
Auth.auth().createUser(withEmail: email!, password: pass!) { (user, error) in
if error == nil {
print("You have successfully signed up")
//Goes to the Setup page which lets the user take a photo for their profile picture and also chose a username
let vc = self.storyboard?.instantiateViewController(withIdentifier: "Home")
self.present(vc!, animated: true, completion: nil)
} else {
let alertController = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
}
}
}
}
Related
My xcode error - Thread 1: "Unsupported type: UITextField for value <UITextField: 0x7fdaa2f20380; frame = (134 168; 97 34); text = 'email'; .....
Here is my Viewcontroller:-
import UIKit
import FirebaseFirestore
import FirebaseAuth
import Stripe
import FirebaseFunctions
class SignUpViewController: UIViewController {
var paymentContext = STPPaymentContext()
#IBOutlet weak var email: UITextField!
#IBOutlet weak var password: UITextField!
#IBOutlet weak var passwordConfirm: UITextField!
#IBAction func signUpAction(_ sender: Any) {
if password.text != passwordConfirm.text {
let alertController = UIAlertController(title: "Password Incorrect", message: "Please re-type password", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
} else {
Auth.auth().createUser(withEmail: email.text!, password: password.text!) {
(user, error) in
if error == nil {
self.performSegue(withIdentifier: "signupToHome", sender: self)
}
else {
let alertController = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
}
}
}
Functions.functions().httpsCallable("createStripeUser").call(["email": email]) {
(result, error) in
if let error = error {
debugPrint(error.localizedDescription)
return
}
self.dismiss(animated: true)
}
}
}
Here is the screenshot of my error:-
Earlier the everything was working fine but out of nowhere it started showing this error. what went wrong ?
I have view controllers connected with my code that include a login page and a sign up page, I've started a firebase project and connected with my Xcode and it successfully connected to the firebase servers. The code below is for my sign up view controller and is supposed to act like a sign up form with email, password and password confirmation but for some reason the build succeeds with no errors but the user that registered does not show up on my firebase user database and the textfields don't act like the way they should (i.e throw an error if password and password confirmation don't match) .
import UIKit
import FirebaseAuth
import FirebaseCore
import Firebase
class SignUpViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBAction func SignUpToHome(sender: AnyObject) {
performSegue(withIdentifier: "SignUpToHome", sender: sender)
}
#IBOutlet weak var email: UITextField!
#IBOutlet weak var password: UITextField!
#IBOutlet weak var passwordConfirm: UITextField!
#IBAction func signUpAction(_ sender: Any) {
//func signUpAction(_ sender: Any) {
//}
if password.text != passwordConfirm.text {
let alertController = UIAlertController(title: "Password Incorrect", message: "Please re-type password", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
}
else{
Auth.auth().createUser(withEmail: email.text!, password: password.text!){ (user, error) in
if error == nil {
self.performSegue(withIdentifier: "SignUpToHome", sender: self)
}
else{
let alertController = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
}
}
}
}
}
I need to my button proceedToAppFeatures to run the code and display an alert of success or failure login(just a single user, for now)
I have tried self.showAlert and self.present
Code:
import UIKit
import FLAnimatedImage
import ImageIO
import UserNotifications//import this to use user notifications
import Firebase
class ViewController: UIViewController, UITextFieldDelegate{
#IBOutlet weak var background: FLAnimatedImageView!
#IBOutlet weak var emailTextField: UITextField!
#IBOutlet weak var passwordTextField: UITextField!
#IBOutlet weak var lblValidationTxt: UILabel!
#IBOutlet weak var lblValidationMessage: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
background.loadGif(name: "neon lights")
passwordTextField.isSecureTextEntry = true// the password will no be visible
emailTextField.delegate = self
passwordTextField.delegate = self
let Tap:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(DismissKeyboard))//here i have used the function to didmiss the keyboard
view.addGestureRecognizer(Tap)
let center = UNUserNotificationCenter.current()
//this initialize the permission that will appear on user screen
center.requestAuthorization(options: [.alert, .sound, .badge]) {
(granted,error) in
//enable or disable features based on the authorization
}
// emailTextField.text = ""
// passwordTextField.text = ""//on view did load to store text field property
}
#objc func DismissKeyboard() {//function that implements the type outside the screen
view.endEditing(true)
}
#IBAction func sigInButton(_ sender: UIButton) {
performSegue(withIdentifier: "userData", sender: true)
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == emailTextField {
textField.resignFirstResponder()
}else{
passwordTextField.becomeFirstResponder()//just to decide which of the buttons will respond after a tab is pressed
passwordTextField.resignFirstResponder()
}
return true
}
func showAlert(title: String, message: String){
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: {(action) in alert.dismiss(animated: true, completion: nil)}))
self.present(alert, animated: true, completion: nil)
}
func isValidEmail(testStr:String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
let emailTest = NSPredicate(format:"SELF MATCHES %#", emailRegEx)
return emailTest.evaluate(with: testStr)
}
#IBAction func proceedToAppFeatures(_ sender: Any) {
let email = isValidEmail(testStr: emailTextField.text!)
if email == false{
self.showAlert(title: "ERROR", message: "This is not a valid e-mail. Please try again")
emailTextField.text = ""
}else{
self.showAlert(title: "Success", message: "Yousucessifully loged in")
//performSegue(withIdentifier: "formPage", sender: true)
}
let myEmail: String!
myEmail = emailTextField.text!
let myPassword: String!
myPassword = passwordTextField.text!
if(myEmail == "leandroaaramos" && myPassword == "123456"){
//performSegue(withIdentifier: "homeSegue", sender: nil)
//code for the truth
print("You are success")
}else if (myEmail.isEmpty && myPassword.isEmpty){
//here i put the alert message
let alert = UIAlertController(title: "Wow", message: "Hold on fill the gaps", preferredStyle: UIAlertController.Style.alert)
//add an action to the alert
alert.addAction(UIAlertAction(title: "Close", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
self.showAlert(title: "Empty field", message: "Try again")
}else {
//here i put the alert message
let alert = UIAlertController(title: "Ops", message: "Your account is not here", preferredStyle: UIAlertController.Style.alert)
//add an action to the alert
alert.addAction(UIAlertAction(title: "Try Again", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
self.showAlert(title: "Sorry", message: "Can't find you.")
}
}
}
I want go to my loginViewController, if the user leandroaaramos and password 123456 was typed.
I'm trying to create an app and I want to show an alert when there is a login error or if the user forget to enter a username and/or password. However, I always get this warning:
Warning: Attempt to present on
whose view is not in the window
hierarchy!
I have tried the other solutions I found here but I still can't fix it. Here's my code:
func createAlert(title: String, message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action) in
self.dismiss(animated: true, completion: nil)
}))
self.present(alert, animated: true, completion: nil)
}
#IBAction func signInPressed(_ sender: Any) {
if usernameTextField.text == "" || passwordTextField.text == "" {
createAlert(title: "Error in form", message: "Please enter an email and password.")
} else {
var activityIndicator = UIActivityIndicatorView()
activityIndicator = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
activityIndicator.center = self.view.center
activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray
view.addSubview(activityIndicator)
activityIndicator.startAnimating()
UIApplication.shared.beginIgnoringInteractionEvents()
PFUser.logInWithUsername(inBackground: usernameTextField.text!, password: passwordTextField.text!, block: { (user, error) in
activityIndicator.stopAnimating()
UIApplication.shared.endIgnoringInteractionEvents()
if error != nil {
var displayErrorMessage = "Please try again later."
let error = error as NSError?
if let errorMessage = error?.userInfo["error"] as? String {
displayErrorMessage = errorMessage
}
self.createAlert(title: "Sign in error", message: displayErrorMessage)
} else {
print("Logged in")
self.performSegue(withIdentifier: "toSignIn", sender: self)
}
})
}
}
UPDATE: Here's the whole view controller
class ViewController: UIViewController {
#IBOutlet var usernameTextField: UITextField!
#IBOutlet var passwordTextField: UITextField!
func createAlert(title: String, message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action) in
self.dismiss(animated: true, completion: nil)
}))
self.present(alert, animated: true, completion: nil)
}
#IBAction func signInPressed(_ sender: Any) {
if usernameTextField.text == "" || passwordTextField.text == "" {
createAlert(title: "Error in form", message: "Please enter an email and password.")
} else {
var activityIndicator = UIActivityIndicatorView()
activityIndicator = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
activityIndicator.center = self.view.center
activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray
view.addSubview(activityIndicator)
activityIndicator.startAnimating()
UIApplication.shared.beginIgnoringInteractionEvents()
PFUser.logInWithUsername(inBackground: usernameTextField.text!, password: passwordTextField.text!, block: { (user, error) in
activityIndicator.stopAnimating()
UIApplication.shared.endIgnoringInteractionEvents()
if error != nil {
var displayErrorMessage = "Please try again later."
let error = error as NSError?
if let errorMessage = error?.userInfo["error"] as? String {
displayErrorMessage = errorMessage
}
self.createAlert(title: "Sign in error", message: displayErrorMessage)
} else {
print("Logged in")
self.performSegue(withIdentifier: "toSignIn", sender: self)
}
})
}
}
override func viewDidAppear(_ animated: Bool) {
if PFUser.current() != nil {
performSegue(withIdentifier: "toSignIn", sender: self)
}
self.tabBarController?.tabBar.isHidden = true
}
override func viewDidLoad() {
super.viewDidLoad()
}
First create UIAlertController such an attribute.
var alertController: UIAlertController?
And you must add this in the viewDidLoad() like this:
override func viewDidLoad() {
super.viewDidLoad()
self.alertController = UIAlertController(title: "Alert", message: "Not images yet", preferredStyle: .alert)
self.alertController?.addAction(UIAlertAction(title: "Close", style: .default))
view.addSubview((alertController?.view)!)
}
So when you press signInButton and login is incorrect you must invoke.
#IBAction func signInPressed(_ sender: Any) {
if usernameTextField.text == "" || passwordTextField.text == "" {
createAlert(title: "Error in form", message: "Please enter an email and password.")
} else {
var activityIndicator = UIActivityIndicatorView()
activityIndicator = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
activityIndicator.center = self.view.center
activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray
view.addSubview(activityIndicator)
activityIndicator.startAnimating()
UIApplication.shared.beginIgnoringInteractionEvents()
PFUser.logInWithUsername(inBackground: usernameTextField.text!, password: passwordTextField.text!, block: { (user, error) in
activityIndicator.stopAnimating()
UIApplication.shared.endIgnoringInteractionEvents()
if error != nil {
self.presentedViewController?.present(self.alertController!, animated: true, completion: nil)
}
}
Whenever We are trying to present UIAlertController inside any closure, We should call it on the main thread like:
DispatchQueue.main.async { [weak self] in
self?.createAlert(title: "Sign in error", message: displayErrorMessage)
}
Try this code for Swift 3
func displayMyAlertMessageError(userMessage:String, titleHead: String)
//define displyMyAlertMessage.
{
let MyAlert = UIAlertController(title: titleHead, message: userMessage, preferredStyle:UIAlertControllerStyle.alert);
let okAction = UIAlertAction(title: "Okay", style: UIAlertActionStyle.default, handler: nil);MyAlert.addAction(okAction);
self.present(MyAlert,animated:true,completion:nil);
}
#IBAction func signInPressed(_ sender: Any) {
if (usernameTextField.text?.isEmpty) || (passwordTextField.text?.isEmpty)
{
createAlert(title: "Error in form", message: "Please enter an email and password.")
}
else
{
//Your code here
}
Change your createAlert method to this,
func createAlert(title: String, message: String, controller: UIViewController) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action) in
self.dismiss(animated: true, completion: nil)
}))
controller.present(alert, animated: true, completion: nil)
}
And then create alerts like this,
self.createAlert(title: "Sign in error", message: "Please try again later.", controller: self)
This might solve your problem.
I am attempting to create a sign up page where people put such info as their email and desired password, after this is completed I want to switch to the next view controller however, I am getting the following error
[StudyBuddy.SignUpViewController signUpButton:]: unrecognized selector sent to instance 0x7fac5e061b80'
SignUpViewController
import UIKit
import Firebase
import CoreData
import CoreLocation
class SignUpViewController: UIViewController {
#IBOutlet weak var emailField: UITextField!
#IBOutlet weak var passwordField: UITextField!
#IBOutlet weak var confirmPasswordField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
if let user = FIRAuth.auth()?.currentUser {
}
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func signupButton(sender: AnyObject)
{
if self.emailField.text == "" || self.passwordField.text == "" {
let alertController = UIAlertController(title: "Oops!", message: "Please enter a valid username and password", preferredStyle: .Alert)
let defaultAction = UIAlertAction(title: "Ok", style: .Cancel, handler: nil)
self.presentViewController(alertController, animated: true, completion: nil)
}
else if self.confirmPasswordField.text != self.passwordField.text {
let passwordAlert = UIAlertController(title: "Oops!", message: "Passwords do not match", preferredStyle: .Alert)
let passwordAction = UIAlertAction(title: "Ok", style: .Cancel, handler: nil)
self.presentViewController(passwordAlert, animated: true, completion: nil)
}
else {
FIRAuth.auth()?.createUserWithEmail(emailField.text!, password: passwordField.text!, completion: {(user, error) in
if error == nil {
self.performSegueWithIdentifier("goToSignUp", sender: sender)
}
else {
let createAlert = UIAlertController(title: "There was a problem", message: "There was a problem creating your account, please check the information you provided and try again", preferredStyle: .Alert)
let createAction = UIAlertAction(title: "Ok", style: .Cancel, handler: nil)
self.presentViewController(createAlert, animated: true, completion: nil)
}
})
}
}
You need to change your signupButton method declaration with signUpButton because inside your declaration u is lower latter for up you need to change it with Up because method name and property name are case sensitive or else change to selector with this signupButton one where you are adding target for button.