Writing User Data to Firebase After Creating New User Account - swift

I am currently trying to write the users information to firebase's database after using the create user function FIRAuth.auth()?.createUser
Under this function I attempt to insert the data into the database like this:
FIRAuth.auth()?.createUser(withEmail: self.emailField.text!, password: self.passwordField.text!) { (user, error) in
if error == nil
{
let email = self.emailField.text
let firstName = self.firstnameField.text
let lastName = self.lastnameField.text
self.ref.child((user?.uid)!).setValue(["firstName": firstName,"lastName": lastName,"email": email])
self.performSegue(withIdentifier: "createaccountLandingPage", sender: sender)
}
It also may be important to mention that under my view controller I create the reference to the database using:
var ref = FIRDatabase.database().reference().child("users") //root database
My outlets are all correct, but I am getting this error:
Thread 1: signal SIGABRT
Any suggestions on what I may be doing incorrectly?
EDIT** Here is all my code in the signup view controller
import UIKit
import Firebase
import FirebaseDatabase
class CreateAccountViewController: UIViewController {
var ref = FIRDatabase.database().reference().child("users") //root database
#IBOutlet weak var firstnameField: UITextField!
#IBOutlet weak var lastnameField: UITextField!
#IBOutlet weak var emailField: UITextField!
#IBOutlet weak var passwordField: UITextField!
#IBOutlet weak var confirmpasswordField: UITextField!
#IBOutlet weak var createAccountButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
if (FIRAuth.auth()?.currentUser) != nil
{
}
else
{
}
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func createAccountAction(_ sender: AnyObject)
{
if self.confirmpasswordField.text != self.passwordField.text
{
}
else
{
FIRAuth.auth()?.createUser(withEmail: self.emailField.text!, password: self.passwordField.text!) { (user, error) in
if error == nil
{
let user = FIRAuth.auth()?.currentUser.uid
let email = self.emailField.text
let firstName = self.firstnameField.text
let lastName = self.lastnameField.text
self.ref.child("users").child("\(user)").setValue(["firstName": firstName,"lastName": lastName,"email": email])
self.performSegue(withIdentifier: "createaccountLandingPage", sender: sender)
}
else
{
let alertController = UIAlertController(title: "Oops!", message: error?.localizedDescription, preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
}
}
}
}
EDIT*** here is a screenshot of the error
EDIT**** here is a screenshot of my podfile and when it is updated I recieve no errors in the terminal.
EDIT***** Screenshots of console.
1stScreenshotConsole
2ndScreenshotConsole

You have to create a reference to your database like this
Var ref: FIRDatabaseReference!
Then you initialize your database in your viewDidLoad like this
Ref = FIRDatabase.database().reference()
I wrote the whole code below, excuse the syntax errors because I am answering your question on an iPad.
import UIKit
import Firebase
import FirebaseDatabase
class CreateAccountViewController: UIViewController {
var ref = FIRDatabaseReference! //create a reference for your database
#IBOutlet weak var firstnameField: UITextField!
#IBOutlet weak var lastnameField: UITextField!
#IBOutlet weak var emailField: UITextField!
#IBOutlet weak var passwordField: UITextField!
#IBOutlet weak var confirmpasswordField: UITextField!
#IBOutlet weak var createAccountButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
//initialize your database
ref = FIRDatabase.database().reference()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func createAccountAction(_ sender: AnyObject)
{
if self.confirmpasswordField.text != self.passwordField.text
{
}
else
{
FIRAuth.auth()?.createUser(withEmail: self.emailField.text!, password: self.passwordField.text!) { (user, error) in
if error == nil
{
let user = FIRAuth.auth()?.currentUser.uid //get the users UID after registering
let email = self.emailField.text
let firstName = self.firstnameField.text
let lastName = self.lastnameField.text
self.ref.child("users").child("\(user!)").setValue(["firstName": "\(firstName!)", "lastName": "\(lastName!)", "email": "\(email!)"])
self.performSegue(withIdentifier: "createaccountLandingPage", sender: sender)
}
else
{
let alertController = UIAlertController(title: "Oops!", 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

Force unwrapping nil optional for UIImageView when transitioning to view controller

I'm running into an error when transitioning to view controllers by overriding the built-in prepare() function in Swift. I have a UIImageView for backgrounds on my screens. Here is the code for two of the view controllers in question.
import UIKit
import FirebaseAuth
class HomeVC: UIViewController {
#IBOutlet weak var signOutButton: UIButton!
#IBOutlet weak var backgroundImageView: UIImageView!
#IBOutlet weak var friendsNavButton: UIButton!
#IBOutlet weak var homeNavButton: UIButton!
#IBOutlet weak var profileNavButton: UIButton!
#IBOutlet weak var bumpButton: UIButton!
#IBOutlet weak var welcomeLabel: UILabel!
#IBOutlet weak var doNotDisturbLabel: UILabel!
#IBOutlet weak var doNotDisturbButton: UIButton!
var userName = ""
var dndIsOn: Bool = false
#IBAction func dndToggled(_ sender: Any) {
dndIsOn = !dndIsOn
User.current.available = !dndIsOn
FirestoreService.db.collection(Constants.Firestore.Collections.users).document(User.current.uid).updateData([Constants.Firestore.Keys.available : !dndIsOn])
if dndIsOn {
print("DND is on!")
setupDNDUI()
} else if !dndIsOn {
print("DND is off!")
setupActiveUI()
}
}
#IBAction func signOutTapped(_ sender: Any) {
let firAuth = Auth.auth()
do {
try firAuth.signOut()
} catch let signOutError as NSError {
print ("Error signing out: %#", signOutError)
}
print("Successfully signed out")
}
#IBAction func bumpTapped(_ sender: Any) {
self.performSegue(withIdentifier: Constants.Segues.toCall, sender: self)
}
#IBAction func friendsNavTapped(_ sender: Any) {
self.performSegue(withIdentifier: Constants.Segues.toFriends, sender: self)
}
#IBAction func profileNavTapped(_ sender: Any) {
let nav = self.navigationController //grab an instance of the current navigationController
DispatchQueue.main.async { //make sure all UI updates are on the main thread.
nav?.view.layer.add(CATransition().segueFromLeft(), forKey: nil)
nav?.pushViewController(ProfileVC(), animated: false)
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.setNavigationBarHidden(true, animated: true)
self.backgroundImageView.contentMode = UIView.ContentMode.scaleAspectFill
doNotDisturbLabel.isHidden = true
if !userName.isEmpty {
welcomeLabel.text = "Welcome Back, " + userName + "!"
} else {
welcomeLabel.text = ""
}
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .darkContent
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let friendsVC = segue.destination as? FriendsVC else {
return
}
FirestoreService.db.collection(Constants.Firestore.Collections.users).document(User.current.uid).getDocument { (snapshot, err) in
if let err = err {
print(err.localizedDescription)
} else {
let data = snapshot!.data()!
let requests = data[Constants.Firestore.Keys.requests] as? [String]
if let requests = requests {
friendsVC.requests = requests
}
}
}
}
class FriendsVC: UIViewController {
//var friends: [Friend] = User.current.friends
var friends: [User] = []
var requests: [String]?
#IBOutlet weak var requestsNumberLabel: UILabel!
#IBOutlet weak var backgroundImageView: UIImageView!
#IBOutlet weak var friendRequestsButton: UIButton!
#IBOutlet weak var homeNavButton: UIButton!
#IBOutlet weak var friendsTitle: UILabel!
#IBOutlet weak var friendTableView: UITableView!
#IBOutlet weak var addFriendButton: UIButton!
#IBOutlet weak var tableViewTopConstraint: NSLayoutConstraint!
#IBAction func friendRequestsTapped(_ sender: Any) {
self.performSegue(withIdentifier: Constants.Segues.toRequests, sender: self)
}
#IBAction func homeNavTapped(_ sender: Any) {
let nav = self.navigationController //grab an instance of the current navigationController
DispatchQueue.main.async { //make sure all UI updates are on the main thread.
nav?.view.layer.add(CATransition().segueFromLeft(), forKey: nil)
nav?.pushViewController(HomeVC(), animated: false)
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.setNavigationBarHidden(true, animated: true)
backgroundImageView.contentMode = UIView.ContentMode.scaleAspectFill
friendTableView.backgroundView?.backgroundColor = .white
friendsTitle.isHidden = false
UserService.getUserArray(uids: User.current.friendUids, completion: { (users) in
guard let users = users else {
print("User has no friends")
return
}
self.friends = users
self.friendTableView.reloadData()
})
guard let requests = self.requests else {
friendRequestsButton.isHidden = true
requestsNumberLabel.isHidden = true
self.tableViewTopConstraint.constant = 0
return
}
requestsNumberLabel.text = requests.count.description
// Do any additional setup after loading the view.
friendTableView.delegate = self
friendTableView.dataSource = self
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let homeVC = segue.destination as? HomeVC {
homeVC.userName = User.current.firstName
} else if let requestsVC = segue.destination as? RequestsVC {
UserService.getUserArray(uids: self.requests!) { (requesters) in
if let requesters = requesters {
requestsVC.requesters = requesters
}
}
}
}
}
When my app loads into the home screen, there is no problem, and when a button is tapped to transition to FriendsVC, there is no problem. However, when I try to initiate the transition from HomeVC to ProfileVC or from FriendVC to HomeVC, I get the error: "Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value" at the self.backgroundImageView.contentMode = UIView.ContentMode.scaleAspectFill lines in my viewDidLoad methods. These segues have something in common in that these are the ones where I override the prepare() function, but I'm not sure what I'm doing wrong

Get data writing in UITextField

I am creating a form for taking measurements and I therefore have several text files. I need to be able to retrieve what the user writes in the textField. I tried several methods but I can't find a way to get there. Can you give me a lead?
Here is my code:
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
var myTextField = UITextField()
#IBOutlet weak var wristFlex: UITextField!
#IBOutlet weak var wristExtension: UITextField!
#IBOutlet weak var firstPhalanx: UITextField!
#IBOutlet weak var secondPhalanx: UITextField!
#IBOutlet weak var thirdPhalanx: UITextField!
#IBOutlet weak var forearmLenght: UITextField!
#IBOutlet weak var handLenght: UITextField!
#IBOutlet weak var fingerLenght: UITextField!
#IBOutlet weak var forearmCirecumference: UITextField!
#IBOutlet weak var wristCirecumference: UITextField!
#IBOutlet weak var fingerCirecumference: UITextField!
#IBOutlet weak var handCirecumference: UITextField!
#IBOutlet weak var validatedPressed: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
wristFlex.delegate = self
wristExtension.delegate = self
firstPhalanx.delegate = self
secondPhalanx.delegate = self
thirdPhalanx.delegate = self
forearmLenght.delegate = self
handLenght.delegate = self
fingerLenght.delegate = self
forearmCirecumference.delegate = self
wristCirecumference.delegate = self
fingerCirecumference.delegate = self
handCirecumference.delegate = self
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(textFieldTextDidChange), name: UITextField.textDidChangeNotification, object: nil)
}
// Notifications:
#objc func textFieldTextDidChange(ncParam: NSNotification) {
print("UItextFieldTextDidChange = \(ncParam)")
}
#objc func keyboardWillHide(notification: NSNotification) {
// move back the root view origin to zero
self.view.frame.origin.y = 0
}
#objc func keyboardWillShow(notification: NSNotification) {
guard let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else {
// if keyboard size is not available for some reason, dont do anything
return
}
// move the root view up by the distance of keyboard height
self.view.frame.origin.y = 0 - keyboardSize.height
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
view.endEditing(true)
}
#IBAction func validatedPressed(_ sender: AnyObject) {
if wristFlex.text == "" || wristExtension.text == "" || firstPhalanx.text == "" || secondPhalanx.text == "" || thirdPhalanx.text == "" || forearmLenght.text == "" || handLenght.text == "" || fingerLenght.text == "" || forearmCirecumference.text == "" || wristCirecumference.text == "" || fingerCirecumference.text == "" || handCirecumference.text == "" {
let alertController = UIAlertController(title: "Erreur", message: " Tous les champs ne sont pas remplis", preferredStyle: .alert)
let alertAction = UIAlertAction(title: "Ok", style: .default, handler: nil)
alertController.addAction(alertAction)
present(alertController, animated: true, completion: nil)
return
}
dismiss(animated: true, completion: nil)
}
internal func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
print("")
return true
}
}
You can use the textFieldDidEndEditing method from the UITextfieldDelegate.
This method gets called when a user is done with his entry. Then you can access variables with textField.text
The example below is an implementation for a case where you have only one textfield. In your case you need to distinguish between the different textfields.
func textFieldDidEndEditing(_ textField: UITextField,
reason: UITextField.DidEndEditingReason){
if let value = textField.text {
print(value)
}
}
Hope this helps!
To retrieve what the user writes in the UITextFields, you can access their text properties with something like textField.text.
More specifically in your case something like wristFlex.text, or thirdPhalanx.text can work, and so on, for all of your UITextFields.
Hope this helps someone!

Facebook login user data in Authentication doesn’t show in firebase consoles

Every time, when I use a Facebook account to log in the application is supposed to have identified email shows up on the Firebase console but it doesn’t work properly. Users can use their Facebook account to access the application, but the problem is my profile page always got a crash when I attempt to make that page shows email of the users up. but if I use an email account to log in it doesn’t have any problem the email that I used to sign up able to shows up normally.
I have done everything in this link but can’t fix this problem.
https://firebase.google.com/docs/auth/ios/facebook-login
On the profile page, I use this code to call the email and user
import UIKit
import Firebase
import FirebaseAuth
import FacebookLogin
import FacebookCore
import FirebaseStorage
class ProfileViewController: UIViewController {
#IBOutlet weak var nameLabel: UILabel!
#IBOutlet weak var emailLabel: UILabel!
#IBOutlet weak var passTextField: UITextField!
#IBOutlet weak var changeNameText: UITextField!
#IBOutlet weak var menuButton: UIBarButtonItem!
#IBOutlet weak var imageProfile: UIImageView!
#IBOutlet weak var alertButton: UIBarButtonItem!
let imageUniqueName = UUID().uuidString
let imagePicker = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
let user = Auth.auth().currentUser
setUserDataToView(withFIRUser: user!)
customizeNavBar()
sideMenus()
let tapGesture = UITapGestureRecognizer()
tapGesture.addTarget(self, action: #selector(ProfileViewController.openGallery(tapGesture:)))
imageProfile.isUserInteractionEnabled = true
imageProfile.addGestureRecognizer(tapGesture)
imageProfile.drawAsCircle()
}
func setUserDataToView(withFIRUser user: User) {
nameLabel.text = user.displayName
emailLabel.text = "อีเมล์ : \(user.email!)"
}
this is all code on my LoginViewController page
import UIKit
import Firebase
import FirebaseAuth
import FBSDKCoreKit
import FBSDKLoginKit
import FBSDKCoreKit
import FacebookLogin
import FacebookCore
class LoginViewController: UIViewController, FBSDKLoginButtonDelegate {
func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {
if error != nil {
print("โปรดตรวจสอบใหม่อีกรอบ", error.localizedDescription)
} else if result.isCancelled {
} else {
let credential = FacebookAuthProvider.credential(withAccessToken: FBSDKAccessToken.current().tokenString)
Auth.auth().signInAndRetrieveData(with: credential) { (authResult, error) in
ProgressHUD.showSuccess("ยินดีต้อนรับ")
self.performSegue(withIdentifier: "Main", sender: self)
}
}
}
func loginButtonDidLogOut(_ loginButton: FBSDKLoginButton!) {
ProgressHUD.showSuccess("ออกจากระบบสำเร็จ")
}
let loginButton = FBSDKLoginButton()
//Textfields pre-linked with IBOutlets
#IBOutlet var emailTextfield: UITextField!
#IBOutlet var passwordTextfield: UITextField!
#IBOutlet weak var facebookButton: FBSDKLoginButton!
override func viewDidLoad() {
super.viewDidLoad()
loginButton.delegate = self
loginButton.readPermissions = ["public_profile", "email"]
self.navigationController?.setNavigationBarHidden(true, animated: false)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func logInPressed(_ sender: AnyObject) {
//TODO: Log in the user
Auth.auth().signIn(withEmail: emailTextfield.text!, password: passwordTextfield.text!) { (user, error) in
if error != 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!)
}else{
ProgressHUD.showSuccess("ยินดีต้อนรับ")
self.performSegue(withIdentifier: "Main", sender: self)
}
}
}
#IBAction func onClickPassword(_ sender: Any) {
if self.passwordTextfield.isSecureTextEntry == true {
self.passwordTextfield.isSecureTextEntry = false
}
else {
self.passwordTextfield.isSecureTextEntry = true
}
}
override func viewDidAppear(_ animated: Bool){
super.viewDidAppear(animated)
if Auth.auth().currentUser != nil {
self.performSegue(withIdentifier: "Main", sender: nil)
}
}
}
enter image description here

Swift 4 how to print text to label

I am trying to print text into a text field like this:
How to do that the right way?
else {
weak var worgnlogin: UILabel! {
worgnlogin.text = ("brugernavn eller password er skrevet forkert")
}
}
Here you have my main ViewController code I have made an array with all users infomation, as I will loop through and get the right user to login:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var txtUserName: UITextField!
#IBOutlet weak var txtPassword: UITextField!
#IBOutlet weak var worgLogin: UILabel!
let user1 = ["user": "Karsten","userID":"1","userName":"Kalle","passWord":"1234" ]
let user2 = ["user": "Rene","userID":"2","userName":"Rene" ,"passWord":"1234" ]
let user3 = ["user": "Johan","userID":"3","userName":"Johan","passWord":"1234" ]
override func viewDidLoad() {
super.viewDidLoad()
let array = [user1,user2,user3]
UserDefaults.standard.set(array, forKey: "users")
// Do any additional setup after loading the view, typically from a nib.
if UserDefaults.standard.bool(forKey: "ISUSERLOGGEDIN") == true {
//user is already logged in just navigate him to home screen
let homeVc = self.storyboard?.instantiateViewController(withIdentifier: "HomeVC") as! HomeVC
self.navigationController?.pushViewController(homeVc, animated: false)
}
}
#IBAction func authenticateUser(_ sender: Any) {
if txtUserName.text == "userName" && txtPassword.text == "passWord" {
//navigate to home screen
UserDefaults.standard.set(true, forKey: "ISUSERLOGGEDIN")
let homeVc = self.storyboard?.instantiateViewController(withIdentifier: "HomeVC") as! HomeVC
self.navigationController?.pushViewController(homeVc, animated: true)
}else {
displayMyAlertMessage(userMessage: "Brugernavn eller Password er skrevet forkert");
return;
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func displayMyAlertMessage(userMessage:String)
{
let myAlert = UIAlertController(title:"Alert", message:userMessage, preferredStyle: UIAlertController.Style.alert);
let okAction = UIAlertAction(title:"Ok", style:UIAlertAction.Style.default, handler:nil);
myAlert.addAction(okAction);
self.present(myAlert, animated:true, completion:nil);
}
}
i hobe this make a better understanding :)
worgnlogin.text = "brugernavn eller password er skrevet forkert"
First create an IBOutlet for a label:
#IBOutlet weak var worgnLoginLabel: UILabel!
Then in your else statement write:
self.worgnLoginLabel.text = “your message”

user Log In, let the users in without errors (SWIFT) (Parse)

i'm making an app that required Logging In. the problem is when i run my app to try it and type wrong user info it proceed to the next view controller without giving the error !. Heres my code i don't whats the problem !
{
#IBOutlet weak var ActivityIndicator: UIActivityIndicatorView!
#IBOutlet weak var Message: UILabel!
#IBOutlet weak var UsernameTextField: UITextField!
#IBOutlet weak var PasswordTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
ActivityIndicator.hidden = true
ActivityIndicator.hidesWhenStopped = true
// Do any additional setup after loading the view.
}
#IBAction func LogInButtonTapped(sender: AnyObject) {
LogIn()
}
func LogIn() {
// Start activity indicator
ActivityIndicator.hidden = false
ActivityIndicator.startAnimating()
// if there is a user
var user = PFUser()
user.username = UsernameTextField.text
user.password = PasswordTextField.text
PFUser.logInWithUsernameInBackground(UsernameTextField.text, password:PasswordTextField.text) {
(user: PFUser?, error: NSError?) -> Void in
if user != nil {
dispatch_async(dispatch_get_main_queue()) {
self.performSegueWithIdentifier("LogInToHomeVC", sender: self)}
println("Logged In")
} else {
self.ActivityIndicator.stopAnimating()
if let Message: AnyObject = error!.userInfo!["error"] {
self.Message.text = "\(Message)"}
println("Could Not Find User")
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
so the question is how to let the user try again and not let him enter the Home Page?