iOS firebase login - ios

my firebase login screen crashes when trying to login
Here is the error:
2018-05-02 09:39:25.937258-0400 noteCollab[2418:625945] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'The link provided is not valid for email/link sign-in. Please check the link by calling isSignInWithEmailLink:link: on Auth before attempting to use it for email/link sign-in.'
* First throw call stack:
(0x1837d6d8c 0x1829905ec 0x1837d6c6c 0x1008aa3e0 0x10089c0b8 0x10089cd08 0x10089b808 0x101a29260 0x101a29220 0x101a37e80 0x101a2c730 0x101a38dd8 0x101a3febc 0x1833fbe70 0x1833fbb08)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
Here is my code:
//
// signinViewController.swift
// noteCollab
//
// Created by James Hall on 5/2/18.
// Copyright © 2018 James Hall. All rights reserved.
//
import UIKit
import Firebase
import FirebaseAuth
class signinViewController: UIViewController {
#IBOutlet weak var signInSelector: UISegmentedControl!
#IBOutlet weak var signInLabel: UILabel!
#IBOutlet weak var emailTextField: UITextField!
#IBOutlet weak var passwordTextField: UITextField!
#IBOutlet weak var signInButton: UIButton!
var isSignIn:Bool = true
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 signInSelectorChanged(_ sender: UISegmentedControl) {
isSignIn = !isSignIn
if isSignIn {
signInLabel.text = "Sign In"
signInButton.setTitle("Sign In", for: .normal)
}else{
signInLabel.text = "Register"
signInButton.setTitle("Register", for: .normal)
}
}
#IBAction func signInButtonTapped(_ sender: UIButton) {
if let email = emailTextField.text, let pass = passwordTextField.text{
//check if its sign in or register
if isSignIn{
//sign in the user with Firebase
Auth.auth().signIn(withEmail: email, link: pass) { (user, error) in
// check that user isnt nil
if error != nil{
print("cant sign in user")
}else{
self.performSegue(withIdentifier: "goToHome", sender: self)
}
}
}else{
//register the user with Firebase
Auth.auth().createUser(withEmail: email, password: pass) { (user, error) in
// check that user isnt nil
if let u = user {
//user is found, go to home
self.performSegue(withIdentifier: "goToHome", sender: self)
}else{
//error: check error and show message
}
}
}
}
}
}

Your sign in code is looking for an email link instead of a password. Simply change the word "link:" to "password:" and you should be all set.
Auth.auth().signIn(withEmail: email, password: password)

Related

How to add a user with setValue from Firebase Reading and writing data in ios

I am a newbie in Swift and I am learning by building a social media application.
I am struck at trying to implement self.ref.child("users").child(user.uid).setValue(["username": username]) in my code (from https://firebase.google.com/docs/database/ios/read-and-write).
I have been following the instructions of Kasey Schlaudt and at this point of the tutorial https://youtu.be/GrRggN41VF0?t=619 he tried to add a user with setValue as shown in the Firebase documentation I have linked. The errors I get in the line self.ref.child("users").child(user.uid).setValue(["username": username]) are
Use of unresolved identifier 'user' and Use of unresolved identifier 'username'.
My code so far (with some little changes from the original code in the video in my signInPress function) is
import UIKit
import Firebase
import SwiftKeychainWrapper
class ViewController: UIViewController {
#IBOutlet weak var UserImageView: UIButton!
#IBOutlet weak var usernameField: UITextField!
#IBOutlet weak var emailField: UITextField!
#IBOutlet weak var passwordField: UITextField!
override func viewDidLoad()
{
super.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool)
{
if let _ : Bool = KeychainWrapper.standard.string(forKey: "uid") != nil
{
self.performSegue(withIdentifier: "toFeed", sender: nil)
}
}
func storeUserData(userID: String)
{
//---------------------------problematic line---------------------------
//from https://firebase.google.com/docs/database/ios/read-and-write
//from https://youtu.be/GrRggN41VF0?t=619
self.ref.child("users").child(user.uid).setValue(["username": username])
([
"username": usernameField.text
])
}
#IBAction func signInPress(_ sender: Any)
{
//this way you make sure there is a property inside emailField.text and you have a variable you can easily use
if let email = emailField.text, let password = passwordField.text
{
Auth.auth().signIn(withEmail: email, password: password)
{ (result, error) in
if error != nil && self.usernameField.text!.isEmpty && self.UserImageView.image != nil
{
Auth.auth().createUser(withEmail: email, password: password)
{ (result, error) in
self.storeUserData(userID: (result?.user.uid)!)
KeychainWrapper.standard.set((result?.user.uid)!, forKey: "KEY_UID")
self.performSegue(withIdentifier: "toFeed", sender: nil)
}
} else
{
KeychainWrapper.standard.set((result?.user.uid)!, forKey: "KEY_UID")
self.performSegue(withIdentifier: "toFeed", sender: nil)
}
}
}
}
}
I would very much appreciate any indication as to why the error does not occur for Kasey and what I might need to change to do the same process.
Thank you in advance !
You're actually pretty close, more of a typo issue. See that your storeUserData function is expecting a string called userID? That's what's needed in the line to store that data instead of user.uid
func storeUserData(userID: String) {
let username = self.usernameField.text
self.ref.child("users").child(userID).setValue(["username": username])
here ^^^^^^ userID instead of user.uid
}

crashing: _finishDecodingLayoutGuideConnections:] unrecognized selector sent to instance

I am working in X-code 9 beta Swift 4, and can run and build but get the following error and only a white screen loads:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[myapp.logInVC _finishDecodingLayoutGuideConnections:]: unrecognized selector sent to instance 0x10251ead0'
Not sure what _finishDecodingLayoutGuideConnections is?
I checked all my selectors, but didn't see an issue. This is a login screen using Firebase, and my hope would be if login is successful it will load the View Controller.
Any help would be much appreciated!
class logInVC: UIViewController {
#IBOutlet weak var signInSelector: UISegmentedControl!
#IBOutlet weak var signInLabel: UILabel!
#IBOutlet weak var emailTextField: UITextField!
#IBOutlet weak var passwordTextField: UITextField!
var isSignIn:Bool = true
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 signInSelectorChanged(_ sender: UISegmentedControl) {
switch signInSelector.selectedSegmentIndex
{
case 0:
signInLabel.text = "sign in";
case 1:
signInLabel.text = "create account";
default:
break
}
}
#IBAction func signInButtonTapped(_ sender: UIButton) {
if isSignIn {
//validation
if let email = emailTextField.text, let pass = passwordTextField.text
{
//sign in with Firebase
Auth.auth().signIn(withEmail: email, password: pass) { (user, error) in
// make sure user isn't nil
if user != nil {
//user is found, go to AR experience
self.performSegue(withIdentifier: "goToHome" , sender: self)
}
else {
//error, check error and show message
}
}
}
else {
//register with Firebase
Auth.auth().createUser(withEmail: emailTextField.text!, password: passwordTextField.text!) { (user, error) in
// make sure user isn't nil
if user != nil {
//user is found, go to AR experience
self.performSegue(withIdentifier: "goToHome" , sender: self)
}
else {
//error, check error, and show message
}
}
Check whether your IBOutlets and IBActions are properly connected. The error occurs when your XiB and Class files are not properly setup.

Firebase Auth creating users

I can't seem to get this to work. The database portion works and I'm getting user info as intended in the database, but it is not creating users in Firebase Auth. For the following code, it printed "can't register."
Can someone please tell me what I'm doing wrong?
import UIKit
import Firebase
import FirebaseAuth
class AddUserTableViewController: UITableViewController, UITextFieldDelegate {
#IBOutlet weak var firstNameTextField: UITextField!
#IBOutlet weak var emailTextField: UITextField!
#IBAction func saveUserButton(_ sender: Any) {
let ref: FIRDatabaseReference!
ref = FIRDatabase.database().reference()
FIRAuth.auth()?.createUser(withEmail: emailTextField.text!, password: "pass", completion: { (user, error) in
if error != nil {
print ("Can't Register")
}
else {
print ("I don't know what this means")
}
})
ref?.child("Users").childByAutoId().setValue(["First Name": self.firstNameTextField.text, "Email": self.emailTextField.text])
}
Just include Firebase, you don't need to include FirebaseAuth as well on each page.
Here's my working code for FireBase login, I did this from a Youtube tutorial a few weeks ago.
import UIKit
import Firebase
class LoginController: UIViewController {
#IBOutlet weak var menuButton:UIBarButtonItem!
#IBOutlet weak var signinSelector: UISegmentedControl!
#IBOutlet weak var signinLabel: UILabel!
#IBOutlet weak var emailTextField: UITextField!
#IBOutlet weak var passwordTextField: UITextField!
#IBOutlet weak var signinButton: UIButton!
var isSignIn:Bool = true
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func signinSelectorChanged(_ sender: UISegmentedControl) {
//Flip the boolean true to false
isSignIn = !isSignIn
//Check the boolean and set the buttons and labels
if isSignIn {
signinLabel.text = "Sign In"
signinButton.setTitle("Sign In", for: .normal)
}
else {
signinLabel.text = "Register"
signinButton.setTitle("Register", for: .normal)
}
}
#IBAction func signinButtonTapped(_ sender: UIButton) {
//Do some form validation on email and password
if let email = emailTextField.text, let pass = passwordTextField.text
{
//Check if it's signed or register
if isSignIn {
//Sign in the user with Firebase
Auth.auth().signIn(withEmail: email, password: pass, completion: { (user, error) in
//Check that user isn't nil
if let u = user {
//User is found, goto home screen
self.performSegue(withIdentifier: "goToHome", sender: self)
}
else{
//Error: Check error and show message
}
})
}
else {
//Register the user with Firebase
Auth.auth().createUser(withEmail: email, password: pass, completion: { (user, error) in
//Check that user isn't NIL
if let u = user {
//User is found, goto home screen
self.performSegue(withIdentifier: "goToHome", sender: self)
}
else {
//Check error and show message
}
})
}
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
//Dismiss the keyboard when the view is tapped on
emailTextField.resignFirstResponder()
passwordTextField.resignFirstResponder()
}
}

How do I add a sign up page into my Parse app with Swift?

Dose anyone know how I can make a user sign up with parse in Swift Xcode 6.4?
I Have searched everything and can't find one that works.
I Tried this code but it did not work.
It said:
Use of unresolved identifier PFUser
import UIKit
class SignupViewController: UIViewController {
#IBOutlet var usernameTextField: UITextField!
#IBOutlet var passwordTextField: UITextField!
#IBOutlet var emailTextField: UITextField!
#IBOutlet var messageLabel: UILabel!
#IBAction func loginVerifyButton(sender: AnyObject) {
var usrEntered = usernameTextField.text
var pwdEntered = passwordTextField.text
var emlEntered = emailTextField.text
if usrEntered != "" && pwdEntered != "" && emlEntered != "" {
// If not empty then yay, do something
} else {
WrongInfo()
}
}
func userSignUp() {
var user = PFUser()
user.username = usrEntered
user.password = pwdEntered
user.email = emlEntered
}
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.
}
/*
// 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.
}
*/
func WrongInfo(){
var WrongInfo:UIAlertView = UIAlertView(title: "ALL FEILDS REQUIRED", message: "Please use all feilds!", delegate: self, cancelButtonTitle: "ok")
}
}
You need to import Parse , in Appdelegate.swift file! if still getting same error import Parse in signup view controller too
You have to create your own view and then implement it/segue users to it based on the users current status. If they click your sign up button segue them to a custom view and then act accordingly. You would sign them up with a function similar to what you have offered already in your question:
func myMethod() {
var user = PFUser()
user.username = "myUsername"
user.password = "myPassword"
user.email = "email#example.com"
// other fields can be set just like with PFObject
user["phone"] = "415-392-0202"
user.signUpInBackgroundWithBlock {
(succeeded: Bool, error: NSError?) -> Void in
if let error = error {
let errorString = error.userInfo?["error"] as? NSString
// Show the errorString somewhere and let the user try again.
} else {
// Hooray! Let them use the app now.
}
}
You essentially could use the same view you already have since your fields are identical but call different methods depending on the button they select.

Custom Twitter Parse Login in Swift

I want to create custom view controller twitter Parse login. I do not want to use default "loginViewController" fields provided by Parse. I also want to extract user's screen name and profile picture from twitter and save it in Parse. Here is my code.
//SignInController for custom Parse SignIn
import UIKit
import Foundation
import Parse
import ParseUI
class SignInController: UIViewController {
#IBOutlet weak var fbLogin: UIButton! //Facebook login button
#IBOutlet weak var TwitterLogin: UIButton! //Twitter login button
#IBOutlet weak var username: UITextField!
#IBOutlet weak var password: UITextField!
#IBOutlet weak var SignIn: UIButton! //Custom SignIn button for Parse
#IBOutlet weak var signUp: UIButton! //Custom SignUp button for Parse
var actInd: UIActivityIndicatorView=UIActivityIndicatorView (frame: CGRectMake(0, 0, 150, 150)) as UIActivityIndicatorView
override func viewDidLoad() {
super.viewDidLoad()
//Do additional setup after loading the view.
self.actInd.center=self.view.center
self.actInd.hidesWhenStopped=true
self.actInd.activityIndicatorViewStyle=UIActivityIndicatorViewStyle.Gray
view.addSubview(self.actInd)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
//Dispose any resourses that can be recreated.
}
#IBAction func FBLoginAction(sender: AnyObject) {
//Facebook login
}
#IBAction func TwitterLoginAction(sender: AnyObject) {
//Here I want to implement twitter login
}
//Custom Parse SignIn
#IBAction func SignInAction(sender: AnyObject) {
var usernamefield=self.username.text
var passwordfield=self.password.text
if (count(usernamefield.utf16)<4 || count(passwordfield.utf16)<5)
{
alert("Invalid", message: "Username must be greater than 4 and password must be greater than 5")
}
else
{
self.actInd.startAnimating()
PFUser.logInWithUsernameInBackground(usernamefield, password: passwordfield, block: { (user, error) -> Void in
self.actInd.stopAnimating()
if((user) != nil)
{
self.alert("Success", message: "Logged In")
}
else
{
self.alert("Error", message: "\(error)")
}
})
}
}
//Create Account or SignUp Controller
class CreatAccount: UIViewController {
#IBOutlet weak var username: UITextField!
#IBOutlet weak var email: UITextField!
#IBOutlet weak var password: UITextField!
#IBOutlet weak var confirmPassword: UITextField!
#IBOutlet weak var signUp: UIButton!
var actInd: UIActivityIndicatorView=UIActivityIndicatorView (frame: CGRectMake(0, 0, 150, 150)) as UIActivityIndicatorView
override func viewDidLoad() {
super.viewDidLoad()
//Do additional setup after loading the view.
self.actInd.center=self.view.center
self.actInd.hidesWhenStopped=true
self.actInd.activityIndicatorViewStyle=UIActivityIndicatorViewStyle.Gray
view.addSubview(self.actInd)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
//Dispose any resourses that can be recreated.
}
//Custom Parse SignUp
#IBAction func signUpAction(sender: AnyObject) {
var usernamefield=self.username.text
var passwordfield=self.password.text
var emailfield=self.email.text
var confirmpasswordfield=self.confirmPassword.text
if (count(usernamefield.utf16)<4 || count(passwordfield.utf16)<5 || count(confirmpasswordfield.utf16)<5 )
{
alert("Invalid", message: "Username must be greater than 4 and password must be greater than 5")
}
else if(count(emailfield.utf16)<8)
{
alert("Invalid", message: "Please enter a valid email")
}
else if(passwordfield != confirmpasswordfield )
{
alert("Invalid", message: "Passwords mismatch")
}
else
{
self.actInd.startAnimating()
var newUser=PFUser()
newUser.username=usernamefield
newUser.password=passwordfield
newUser.email=emailfield
newUser.signUpInBackgroundWithBlock({ (succeed, error) -> Void in
self.actInd.stopAnimating()
if((error) != nil )
{
self.alert("Invalid", message: "\(error)")
}
else
{
self.alert("Success", message: "Signed Up")
}
})
}
}
Here is my answer for my question. Check TwitterLoginAction.
import UIKit
import Foundation
import Parse
import ParseUI
class SignInController: UIViewController
{
#IBOutlet weak var fbLogin: UIButton!
#IBOutlet weak var TwitterLogin: UIButton!
#IBOutlet weak var username: UITextField!
#IBOutlet weak var password: UITextField!
#IBOutlet weak var SignIn: UIButton!
#IBOutlet weak var signUp: UIButton!
var actInd: UIActivityIndicatorView=UIActivityIndicatorView (frame: CGRectMake(0, 0, 150, 150)) as UIActivityIndicatorView
override func viewDidLoad() {
super.viewDidLoad()
//Do additional setup after loading the view.
self.actInd.center=self.view.center
self.actInd.hidesWhenStopped=true
self.actInd.activityIndicatorViewStyle=UIActivityIndicatorViewStyle.Gray
view.addSubview(self.actInd)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
//Dispose any resourses that can be recreated.
}
#IBAction func FBLoginAction(sender: AnyObject) {
}
#IBAction func TwitterLoginAction(sender: AnyObject) {
PFTwitterUtils.logInWithBlock { (user, error) -> Void in
if (user==nil) {
println(user)
println("Uh oh. The user cancelled the Twitter login.")
return;
} else if ((user?.isNew) != nil) {
println("User signed up and logged in with Twitter!")
} else {
println("User logged in with Twitter!")
}
}
}
//Parse SignIn
#IBAction func SignInAction(sender: AnyObject) {
var usernamefield=self.username.text
var passwordfield=self.password.text
if (count(usernamefield.utf16)<4 || count(passwordfield.utf16)<5)
{
alert("Invalid", message: "Username must be greater than 4 and password must be greater than 5")
}
else
{
self.actInd.startAnimating()
PFUser.logInWithUsernameInBackground(usernamefield, password: passwordfield, block: { (user, error) -> Void in
self.actInd.stopAnimating()
if((user) != nil)
{
self.alert("Success", message: "Logged In")
}
else
{
self.alert("Error", message: "\(error)")
}
})
}
}
}
Here is the code for Twitter Login in Swift 3
PFTwitterUtils.logIn { (user, error) in
if (user==nil) {
print("Uh oh. The user cancelled the Twitter login.")
} else if ((user?.isNew) != nil) {
print("User signed up and logged in with Twitter!")
} else {
print("User logged in with Twitter!")
}
}

Resources