Google signing is signing in automatically, also right after log out. swift 4 - ios

After writing the log in with mail, i'm integrating social logins to my app and starting with Google signin. It now logs in automatically at app start, not if I press the Google login button. If I cancel it at pop up window it throws an Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional valueon the token line in AppDelegate`. Also logging out doesn't prevent to log in automatically again.
It was quite confusing following instruction from Firebase manual for Google login so I sure made some obvious mistake.
Here's the code so far:
AppDelegate:
// start google sign in methods
#available(iOS 9.0, *)
func application(_ application: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any])
-> Bool {
return GIDSignIn.sharedInstance().handle(url,
sourceApplication:options[UIApplicationOpenURLOptionsKey.sourceApplication] as? String,
annotation: options[UIApplicationOpenURLOptionsKey.annotation])
}
func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error?) {
// ...
print("User successfully signed in with Google",user)
guard let idToken = user.authentication.idToken else {
return
}
guard let accessToken = user.authentication.accessToken else {return}
let credentials = GoogleAuthProvider.credential(withIDToken: idToken, accessToken: accessToken)
Auth.auth().signInAndRetrieveData(with: credentials) { (user, error) in
if let error = error {
print("Failed to create user with Google account", error)
return
}
print("Succesfully created new user in Firebase with Google account")
}
if let error = error {
// ...
print("User failed to sign in with Google", error)
return
}
guard let authentication = user.authentication else { return }
let credential = GoogleAuthProvider.credential(withIDToken: authentication.idToken,
accessToken: authentication.accessToken)
// let storyboard = UIStoryboard(name: "Main", bundle: nil)
// var mainVC = self.window?.visibleViewController as? MainNavigationController
// mainVC = storyboard.instantiateViewController(withIdentifier: "MainNavigationController") as? MainNavigationController
}
func sign(_ signIn: GIDSignIn!, didDisconnectWith user: GIDGoogleUser!, withError error: Error!) {
// Perform any operations when the user disconnects from app here.
// ...
}
// end of google sign in
The Google signin should perform a segue to main menu but it doesn't.
Only at first sign in it gets to the desired vc.
Here's the Login class:
import UIKit
import Firebase
import GoogleSignIn
class LoginViewController: UIViewController, GIDSignInUIDelegate {
// outlets
#IBOutlet weak var backGroundImage: UIImageView!
#IBOutlet weak var userNameTextField: UITextField!
#IBOutlet weak var emailTextField: UITextField!
#IBOutlet weak var passwordTextField: UITextField!
#IBOutlet weak var confirmPasswordTextField: UITextField!
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if Auth.auth().currentUser != nil {
self.performSegue(withIdentifier: "skipSegue", sender: nil)
}
}
override func viewDidLoad() {
super.viewDidLoad()
setGoogleButton()
setFacebookButton()
}
// dismiss keyboard on touch outside textfields
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for txt in self.view.subviews {
if txt.isKind(of: UITextField.self) && txt.isFirstResponder {
txt.resignFirstResponder()
}
}
}
private func setGoogleButton() {
GIDSignIn.sharedInstance().uiDelegate = self
GIDSignIn.sharedInstance().signIn()
}
private func setFacebookButton() {
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// Actions
#IBAction func newUserRegisterButton(_ sender: Any) {
if passwordTextField.text != confirmPasswordTextField.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: emailTextField.text!, password: passwordTextField.text!){ (user, error) in
if error == nil {
self.performSegue(withIdentifier: "skipSegue", 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)
}
}
}
}
#IBAction func mailLogin(_ sender: UIButton) {
Auth.auth().signIn(withEmail: emailTextField.text!, password: passwordTextField.text!) { (user, error) in
if error == nil{
self.performSegue(withIdentifier: "skipSegue", 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)
}
}
}
#IBAction func facebookLogin(_ sender: UIButton) {
}
#IBOutlet weak var signInButton: GIDSignInButton!
#IBAction func googleSignInButton(_ sender: GIDSignInButton) {
performSegue(withIdentifier: "skipSegue", sender: self)
}
#IBAction func logoutButton(_ sender: UIButton) {
}
#IBAction func skipButton(_ sender: UIButton) {
performSegue(withIdentifier: "skipSegue", sender: self)
}
}
The sign out:
#IBAction func logOutButton(_ sender: UIButton) {
// firebase auth sign out
let firebaseAuth = Auth.auth()
do {
try firebaseAuth.signOut()
} catch let signOutError as NSError {
print ("Error signing out: %#", signOutError)
}
// GSI log out
GIDSignIn.sharedInstance().signOut()
print("User successfully logged out Firebase with Google account")
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let initial = storyboard.instantiateInitialViewController()
UIApplication.shared.keyWindow?.rootViewController = initial
}
func signOutOverride() {
do {
GIDSignIn.sharedInstance().signOut()
try GIDSignIn.sharedInstance()?.disconnect()
// Set the view to the login screen after signing out
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let initial = storyboard.instantiateInitialViewController()
UIApplication.shared.keyWindow?.rootViewController = initial
// let storyboard = UIStoryboard(name: "SignIn", bundle: nil)
// let loginVC = storyboard.instantiateViewControllerWithIdentifier("SignInVC") as! SignInViewController
// let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
// appDelegate.window?.rootViewController = loginVC
} catch let signOutError as NSError {
print ("Error signing out: \(signOutError)")
}
}
I read many posts about revoking the tokens and disconnect the user from the app, but couldn't implement those solutions as some are in obj-c and others in older swift syntax.
Anyone having same problem as me?
Thank as usual.

After many tries and error,thanks to Google's sarcastically useful documentation, I found out what the problem was. They suggest to put the sign in inside viewDidLoad()' and that obviously get's called every time the VC gets instantiated. I so Moved into the Google sign in button and left the delegate only inviewDidLoad()
It all now works as expected.
override func viewDidLoad() {
super.viewDidLoad()
GIDSignIn.sharedInstance().uiDelegate = self
setFacebookButton()
}
#IBOutlet weak var signInButton: GIDSignInButton!
#IBAction func googleSignInButton(_ sender: GIDSignInButton) {
GIDSignIn.sharedInstance()?.signIn()
performSegue(withIdentifier: "skipSegue", 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)*/
}
}
}
}

When trying to logout/unwind back to the home screen, why would you get a found nil error if there isn't even an optional?

Line where error is:
self.passwordField.delegate = self
Code from the button:
#IBAction func unwindToRed(_ sender: Any) {
do {
try Auth.auth().signOut()
let ViewController1 = ViewController()
let ViewNavigationController = UINavigationController(rootViewController: ViewController1)
self.present(ViewNavigationController, animated: true, completion: nil)
} catch let err {
print(err)
}
}
This is the relevant homepage code:
class ViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var emailField: UITextField!
#IBOutlet weak var passwordField: UITextField!
var userUID: String!
var databaseRef: DatabaseReference!
override func viewDidLoad() {
super.viewDidLoad()
databaseRef = Database.database().reference()
self.passwordField.delegate = self
self.emailField.delegate = self
emailField.attributedPlaceholder = NSAttributedString(string: "Email",
attributes: [NSAttributedString.Key.foregroundColor: UIColor.gray])
passwordField.attributedPlaceholder = NSAttributedString(string: "Password",
attributes: [NSAttributedString.Key.foregroundColor: UIColor.gray])
}
override func viewDidAppear(_ animated: Bool) {
if let _ = KeychainWrapper.standard.string(forKey: "uid") {
self.performSegue(withIdentifier: "tohome", sender: nil)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func signInPressed(_ sender: Any) {
Auth.auth().createUser(withEmail: (emailField.text ?? ""), password: (passwordField.text ?? "")) { (user, error) in
if let _eror = error {
//something bad happning
print(_eror.localizedDescription )
let alert = UIAlertController(title: "Error", message: "Invalid Entry or Duplicate.", preferredStyle: UIAlertController.Style.alert)
let action = UIAlertAction(title: "Ok", style: .default, handler: nil)
alert.addAction(action)
self.present(alert, animated: true, completion: nil)
}else{
//user registered successfully
print(user as Any)
if let userID = user?.uid {
KeychainWrapper.standard.set((userID), forKey: "uid")
let databaseRef = Database.database().reference()
databaseRef.child("people").child(userID).child("users").setValue(self.emailField.text!)
databaseRef.child("people").child(userID).child("postID").setValue(userID)
self.performSegue(withIdentifier: "tohome", sender: nil)
}
}
}
}
#IBAction func loginInPressed(_ sender: Any) {
Auth.auth().signIn(withEmail: (emailField.text ?? ""), password: (passwordField.text ?? "")) { (user, error) in
if let _eror = error {
//something bad happning
print(_eror.localizedDescription )
let alert = UIAlertController(title: "Error", message: "Incorrect Email or Password.", preferredStyle: UIAlertController.Style.alert)
let action = UIAlertAction(title: "Ok", style: .default, handler: nil)
alert.addAction(action)
self.present(alert, animated: true, completion: nil)
}else{
//user registered successfully
print(user as Any)
if let userID = user?.uid {
KeychainWrapper.standard.set((userID), forKey: "uid")
self.performSegue(withIdentifier: "tohome", sender: nil) }
}
}
}
Problem is hiding in this line:
#IBAction func unwindToRed(_ sender: Any) {
do {
try Auth.auth().signOut()
let ViewController1 = ViewController() // <-- This is the problem
let ViewNavigationController = UINavigationController(rootViewController: ViewController1)
self.present(ViewNavigationController, animated: true, completion: nil)
} catch let err {
print(err)
}
}
Because you are using storyboards to create your views, you should instantiate your view controller from storyboard. To do this right please refer to Creating View Controllers from Storyboard.
If you're new to iOS development or you don't know why this is required please refer to this post which will explain instantiating view controller from storyboard vs. creating new instance.

AdMob AD view controller closes immediately after opening

I made a sample app and I'm currently trying to test admobs with a login before it. Here's my code:
AppDelegate.swift
import UIKit
import Firebase
import GoogleMobileAds
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
GADMobileAds.configure(withApplicationID: "ca-app-pub-3940256099942544~1458002511")
return true
}
}
ViewController.swift
import UIKit
import FirebaseAuth
class ViewController: UIViewController {
#IBOutlet weak var emailTextField: UITextField!
#IBOutlet weak var passwordTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {
if(Auth.auth().currentUser != nil)
{
self.presentLoggedInScreen()
}
}
#IBAction func createAccountTapped(_ sender: Any)
{
if let email = emailTextField.text, let password = passwordTextField.text{
Auth.auth().createUser(withEmail: email, password: password, completion: { user, error in
if let firebaseError = error {
let alert = UIAlertController(title: "Error", message: firebaseError.localizedDescription, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: "Default action"), style: .`default`, handler: { _ in
}))
self.present(alert, animated: true, completion: nil)
return
}
self.presentLoggedInScreen()
})
}
}
#IBAction func loginTapped(_ sender: Any)
{
if let email = emailTextField.text, let password = passwordTextField.text{
Auth.auth().signIn(withEmail: email, password: password, completion: { user, error in
if let firebaseError = error {
let alert = UIAlertController(title: "Error", message: firebaseError.localizedDescription, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: "Default action"), style: .`default`, handler: { _ in
}))
self.present(alert, animated: true, completion: nil)
return
}
self.presentLoggedInScreen()
})
}
}
func presentLoggedInScreen()
{
let storyboard:UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let loggedInVC:LoggedInVC = storyboard.instantiateViewController(withIdentifier: "LoggedInVC") as! LoggedInVC
self.present(loggedInVC, animated: true, completion: nil)
}
}
LoggedInVC.swift
import UIKit
import FirebaseAuth
import GoogleMobileAds
class LoggedInVC: UIViewController, GADRewardBasedVideoAdDelegate {
#IBOutlet weak var showAdButton: UIButton!
#IBOutlet weak var logLabel: UILabel!
var rewardBasedAd: GADRewardBasedVideoAd!
override func viewDidLoad() {
super.viewDidLoad()
logLabel.text = ""
showAdButton.isEnabled = false
rewardBasedAd = GADRewardBasedVideoAd.sharedInstance()
rewardBasedAd.delegate = self
rewardBasedAd.load(GADRequest(), withAdUnitID: "ca-app-pub-3940256099942544/1712485313")
}
#IBAction func logoutTapped(_ sender: Any) {
do{
try Auth.auth().signOut()
dismiss(animated: true, completion: nil)
} catch{
print("Problem logging out!");
}
}
#IBAction func buttonPressed(_ sender: Any) {
showAdButton.isEnabled = false
if rewardBasedAd.isReady {
rewardBasedAd.present(fromRootViewController: self)
}
}
func rewardBasedVideoAdDidOpen(_ rewardBasedVideoAd: GADRewardBasedVideoAd) {
logLabel.text?.append("An ad opened. \n")
}
func rewardBasedVideoAdDidClose(_ rewardBasedVideoAd: GADRewardBasedVideoAd) {
logLabel.text?.append("An ad closed. \n")
}
func rewardBasedVideoAdDidReceive(_ rewardBasedVideoAd: GADRewardBasedVideoAd) {
logLabel.text?.append("An ad has loaded. \n")
showAdButton.isEnabled = true
}
func rewardBasedVideoAdDidStartPlaying(_ rewardBasedVideoAd: GADRewardBasedVideoAd) {
logLabel.text?.append("An ad started playing. \n")
}
func rewardBasedVideoAdWillLeaveApplication(_ rewardBasedVideoAd: GADRewardBasedVideoAd) {
logLabel.text?.append("An ad caused focus to leave. \n")
}
func rewardBasedVideoAd(_ rewardBasedVideoAd: GADRewardBasedVideoAd, didFailToLoadWithError error: Error) {
logLabel.text?.append("An ad has failed to load. \n")
print(error)
}
func rewardBasedVideoAd(_ rewardBasedVideoAd: GADRewardBasedVideoAd, didRewardUserWith reward: GADAdReward) {
print("Ad finished.")
}
}
I'll post a video of what's happening, but basically the ad audio plays, it just doesn't keep the actual ad on screen nor append the updates to the label.
https://www.youtube.com/watch?v=BlUjPA_AwZQ&feature=youtu.be
Use This Code....that code is working....
#IBAction func buttonPressed(_ sender: Any) {
//showAdButton.isEnabled = false
if rewardBasedAd.isReady {
self.dismiss(animated: false) { () -> Void in
rewardBasedAd.present(fromRootViewController: self)
}
}
else {
print("Ad wasn't ready")
}
}

Fix logout function

I have the following problem. I try to learn coding since a few weeks and my actually project is an Login-Page.
The concept is the following:
When I open the App, there is the Login Screen and the User can login. This works so far. After the login the user is directed to another view. There is a logout button. And here is the problem. When I click the button, the user get logged out (I proofed this by printing out the current user and got nil) and is returned again to the login screen. But when he is now clicking on the login button without or with wrong data he is getting again to the screen although it appeared the error message.
Where is my fault?
Here is my code:
import UIKit
import Parse
class ViewController: UIViewController {
func displayAlert(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)
}
#IBOutlet weak var benutzer: UITextField!
#IBOutlet weak var passwort: UITextField!
#IBAction func ButtonLogin(_ sender: Any) {
// Hier die Loginfunktion
let activityIndiaktor = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
activityIndiaktor.center = self.view.center
activityIndiaktor.hidesWhenStopped = true
activityIndiaktor.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray
view.addSubview(activityIndiaktor)
activityIndiaktor.startAnimating()
UIApplication.shared.beginIgnoringInteractionEvents()
PFUser.logInWithUsername(inBackground: benutzer.text!, password: passwort.text!, block: { (user, error) in
if user == nil {
var errortext = "Unknown Error! Try again!"
if let error = error {
errortext = error.localizedDescription
}
self.displayAlert(title: "Login error", message: errortext)
}else{
print("Login done!")
let viewController:UIViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "Main") as! UIViewController
self.present(viewController, animated: true, completion: nil)
// UIApplication.shared.endIgnoringInteractionEvents()
// activityIndiaktor.stopAnimating()
}
activityIndiaktor.stopAnimating()
UIApplication.shared.endIgnoringInteractionEvents()
return
})
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
And here for the other view:
import UIKit
import Parse
class MainViewController: UIViewController {
#IBAction func Logout(_ sender: Any) {
PFUser.logOut()
let viewController:UIViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "LoginSeite") as! UIViewController
self.present(viewController, animated: true, completion: nil)
}
#IBOutlet weak var LabelWillkommen: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let user = String(describing: PFUser.current()!.username!)
LabelWillkommen.text = "Welcome \(user)!"
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
In your MainViewController Just change your logout button action with below code snippet
#IBAction func Logout(_ sender: Any) {
PFUser.logOut()
if PFUser.current()?.sessionToken == nil {
let viewController:UIViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "LoginSeite") as! UIViewController
self.present(viewController, animated: true, completion: nil)
}
}
Hope this will help you
I checked everything again. I couldn't find the mistake. The Logout works but the if case still thinks, the user is logged in. Can I maybe reload the View or reload the if statement or something like that? Or other ideas?

iOS firebase authentication with Facebook

Hi i tried to make Firebase Facebook Authentication.
But there are some problems. I can get Facebook Email by Firebase,
but if i change the view after login success, I cannot get Facebook Email by
Auth.auth().currentUser?.email
I can check my Facebook email on Firebase Authentication Console.
Google, and normal email authentication works, but facebook is not.
this is my code
class ViewController: UIViewController, GIDSignInUIDelegate, FBSDKLoginButtonDelegate{
// facebook Login
func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult?, error: Error!) {
if result?.token == nil {return}
let credential = FacebookAuthProvider.credential(withAccessToken: FBSDKAccessToken.current().tokenString)
Auth.auth().signIn(with: credential) { (user, error) in
if let error = error {
print(error)
return
}
}
FBSDKLoginManager().logOut()
}
// facebook logout
func loginButtonDidLogOut(_ loginButton: FBSDKLoginButton!) {
}
#IBOutlet weak var email: UITextField!
#IBOutlet weak var password: UITextField!
#IBOutlet weak var facebookLogin: FBSDKLoginButton!
override func viewDidLoad() {
super.viewDidLoad()
GIDSignIn.sharedInstance().uiDelegate = self
facebookLogin.delegate = self
facebookLogin.readPermissions = ["email"]
Auth.auth().addStateDidChangeListener { (user, error) in
if user != nil {
self.performSegue(withIdentifier: "home", sender: nil)
}
}
}
#IBAction func googleSignBtn(_ sender: Any) {
GIDSignIn.sharedInstance().signIn()
}
#IBAction func emailLogin(_ sender: Any) {
Auth.auth().createUser(withEmail: self.email.text!, password: self.password.text!) { (user, error) in
if error != nil {
Auth.auth().signIn(withEmail: self.email.text!, password: self.password.text!, completion: { (user, error) in
})
}else{
let alert = UIAlertController(title: "Alert", message: "Sign up Success!", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Confirm", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
}
}
Sometimes Firebase Auth does not return these kind of details. It is a good practice to store all the details in Firebase Database as shown in the below image under the Database.database().reference().child("uid")
User profile Structure

Resources