简体   繁体   中英

swift firebase google sign in not showing on console

I am trying to sign in to firestore auth using the following GoogleSignInViewController but it shows nothing on the firebase console -

 import UIKit
 import Firebase
 import GoogleSignIn

 class GoogleSignInViewController: UIViewController {
 var googleSignIn = GIDSignIn.sharedInstance()
 
 @IBOutlet weak var emailField: UITextField!

 @IBOutlet weak var passwordField: UITextField!

 @IBAction func googleLoginBtnAction(_ sender: UIButton) {
    print("sign in tapped")
    self.googleAuthLogin()
    
    }

 func googleAuthLogin() {
    self.googleSignIn?.presentingViewController = self
    self.googleSignIn?.clientID = "419387986978-pbs8h2drcjk60svqf1d5mgj0pa436r7b.apps.googleusercontent.com"
    self.googleSignIn?.delegate = self
    self.googleSignIn?.signIn()
  }
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "detailseg" {
            let DestView = segue.destination as! DetailsViewController

        }
  }

  }
  
  extension GoogleSignInViewController: GIDSignInDelegate {
    func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
            guard let user = user else {
                print("Uh oh. The user cancelled the Google login.")
                return
            }
            let userId = user.userID ?? ""
            print("Google User ID: \(userId)")
            
            let userIdToken = user.authentication.idToken ?? ""
            print("Google ID Token: \(userIdToken)")
            
            let userFirstName = user.profile.givenName ?? ""
            print("Google User First Name: \(userFirstName)")
            
            let userLastName = user.profile.familyName ?? ""
            print("Google User Last Name: \(userLastName)")
            
            let userEmail = user.profile.email ?? ""
            print("Google User Email: \(userEmail)")
            
            let googleProfilePicURL = user.profile.imageURL(withDimension: 150)?.absoluteString ?? ""
            print("Google Profile Avatar URL: \(googleProfilePicURL)")
            
       }
    
    func sign(_ signIn: GIDSignIn!, didDisconnectWith user: GIDGoogleUser!, withError error: Error!) {
        
    }
   }

It shows the login page as follows ( only for demonstrational purpose) -

在此处输入图像描述

Then, my app (Fireupgoodsa) takes permission from google to sign in -

在此处输入图像描述

Then, google takes permissioin to share my email id. information with the project -

在此处输入图像描述

Then, it goes to the DetailViewController (shown in red color below)-

在此处输入图像描述

Also, it shows alert message in my official email id.that my account was signed in to a new device ie my iOS simulator, which proves that sign in HAS taken place.

在此处输入图像描述

So far, so good -

but there is nothing on the firebase console -

在此处输入图像描述

This also didn't help me - Not getting the email using Google Authentication in Firebase

I had asked a similar bounty question - How to signoutout user from firebase console in swift

The bounty lapsed, but the problem was not sorted.

I have also deleted the project and created a new project. The screenshot of the project overview is shown below -

在此处输入图像描述

Now, why does not it show anything on the Firebase console. Is it something with the settings, project name. Do I need to add a tag container or something? (Also, please see the address bar in the image above to see if something is wrong). What am I missing out on?

This has been bugging me for quite a while.

I am desperate for help.

Please give me a hand with this, will you?

I am posting the complete code for "class GoogleSignInViewController" and "class AppDelegate"-

class GoogleSignInViewController:-

     import UIKit
     import Firebase
     import GoogleSignIn

    class GoogleSignInViewController: UIViewController {
    var googleSignIn = GIDSignIn.sharedInstance()
    @IBOutlet weak var emailField: UITextField!
    @IBOutlet weak var passwordField: UITextField!

    @IBAction func googleLoginBtnAction(_ sender: UIButton) {
    print("sign in tapped")
    self.googleAuthLogin()
     }
     @IBAction func googleLogoutBtnAction(_ sender: Any) {
    let firebaseAuth = Auth.auth()
    do {
     try firebaseAuth.signOut()
    print ("user is signed  out")
    } catch let signOutError as NSError {
     print ("Error signing out: %@", signOutError)
      }
    }
    func googleAuthLogin() {
    self.googleSignIn?.presentingViewController = self
    self.googleSignIn?.clientID = "9727299xxxxx-m0brc61v3a32br7b34pdjxxxxxxxxxxx.apps.googleusercontent.com"
    self.googleSignIn?.delegate = self
    self.googleSignIn?.signIn()
    }
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "detailseg" {
            let DestView = segue.destination as! DetailsViewController
         }
       }

     }
  
  extension GoogleSignInViewController: GIDSignInDelegate {
 func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!){
    if let err = error {
        print ("failed to log into Google", err)
        return
    }

    print("successfully logged into 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, completion: { (user, error) in
        if let err = error {
            print ("failed to create with google account", err)
            return
        }
        print("successfuly logged into Firebase with Google", user?.user.uid)
       })
      }

    func sign(_ signIn: GIDSignIn!, didDisconnectWith user: GIDGoogleUser!, withError error: Error!) {
        
    }
 }

class AppDelegate:-

import UIKit
import GoogleSignIn
import Firebase
import CoreData

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, GIDSignInDelegate    {
 var window: UIWindow?


       func application(_ application: UIApplication,  didFinishLaunchingWithOptions launchOptions:  [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
   
    FirebaseApp.configure()
    
    // Override point for customization after application launch.
    GIDSignIn.sharedInstance().clientID =  FirebaseApp.app()?.options.clientID
    GIDSignIn.sharedInstance().delegate = self
   
    return true
   }

     func application(_ app: UIApplication, open url: URL, options:   [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
    return GIDSignIn.sharedInstance().handle(url as URL?)
  }


    func sign(_ signIn: GIDSignIn!,
          didSignInFor user: GIDGoogleUser!,
          withError error: Error!) {
    
    // Check for sign in error
    if let error = error {
        if (error as NSError).code == GIDSignInErrorCode.hasNoAuthInKeychain.rawValue {
            print("The user has not signed in before or they have since signed out.")
        } else {
            print("\(error.localizedDescription)")
        }
        return
      }
    
    // Get credential object using Google ID token and Google access token
    guard let authentication = user.authentication else {
        return
    }
    let credential = GoogleAuthProvider.credential(withIDToken: authentication.idToken,
                                                   accessToken: authentication.accessToken)
    
    // Authenticate with Firebase using the credential object
    Auth.auth().signIn(with: credential) { (authResult, error) in
        if let error = error {
            print("Error occurs when authenticate with Firebase: \(error.localizedDescription)")
        }
            
        // Post notification after user successfully sign in
       // NotificationCenter.default.post(name: .signInGoogleCompleted, object: nil)
    }

}

    func sign(_ signIn: GIDSignIn!, didDisconnectWith user: GIDGoogleUser!, withError error: Error!) {
     // Perform any operations when the user disconnects from app here.
     print("User has disconnected")
    }

func applicationWillResignActive(_ application: UIApplication) {
    
 // Sent when the application is about to move from active to inactive   state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and  invalidate graphics rendering callbacks. Games should use this method to pause the game.
  }

   func applicationDidEnterBackground(_ application: UIApplication) {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
  }

  func applicationWillEnterForeground(_ application: UIApplication) {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.

  }

func applicationDidBecomeActive(_ application: UIApplication) {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
 }

func applicationWillTerminate(_ application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
 }
}

The above codes works for me and show me signed in FirebaseAuth with my gmail id.:-

在此处输入图像描述

Note -This answer shows just how the user google/gmail sign-in on the FirebaseAuth console(which is what this question is all about). I have not posted the code to show details in the DetailsiewController. I will post that code later when I have designed that.

Furthermore, If you want to write your Firebase Auth User UID to Firestore Document ID you can refer to the " class UserIdtoFirestoreViewController " of the question in the link:-

How to Show Firebase Auth User UID and also my Firestore doc uid as Stripe customer id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM