简体   繁体   English

Firebase发出2个不同的uid -Swift iOS

[英]Firebase issuing out 2 different uid's -Swift iOS

I have all my pods correctly installed. 我已经正确安装了所有吊舱。 My app launches and then when I get to scenes that have to access Firebase I've noticed there's a crash. 我的应用程序启动,然后当我进入必须访问Firebase的场景时,我注意到发生了崩溃。 The reason seems to be that Firebase is issuing me 2 different uid's and the one in Auth doesn't match the one in the Database. 原因似乎是Firebase向我发出了两个不同的uid,而Auth中的一个与数据库中的一个不匹配。

When my app launches in AppDelegate I have code to get the current uid. 当我的应用程序在AppDelegate中启动时,我有获取当前uid的代码。

//This is in App Delegate
let myUserID = FIRAuth.auth()?.currentUser?.uid

print("App Delegate: UID is \(myUserID!)")
//An example print is 'App Delegate: UID is Abcdefg12345'

Next a SignUp scene is presented and in that view controller I have 接下来显示一个SignUp场景,在该视图控制器中,

FIRAuth.auth()?.createUserWithEmail(self.emailTextField.text!, password: self.passwordTextField.text!, completion: {

            //You can access the newly issued uid from user via user!uid
            (user, err) in

print("SignUp: UID is \(user!uid)\n")
//An example print is 'SignUp: UID is Vwxyz67890'

When I access user!uid (from user) I get a totally different uid from what is originally in the AppDelegate. 当我从用户访问user!uid时,我得到的uid与AppDelegate中最初的uid完全不同。

However the uid that I get from user in FIRAuth.auth()?.createUserWithEmail is what's current in Auth but is not recognized in FirebaseDatabase. 但是,我从FIRAuth.auth()?. createUserWithEmail中的用户获得的uid是Auth中当前的内容,但在FirebaseDatabase中无法识别。

The odd thing is the uid that is printed in AppDelegate is what's current in the FirebaseDatabase but is not recognized in Auth. 奇怪的是,AppDelegate中打印的uid是FirebaseDatabase中当前的内容,但在Auth中无法识别。 If this uid is changed upon signing up then it should not be available in the Database 如果在注册时更改了此uid,则它在数据库中不可用

I also have a logout scene and when I press the logout button I get the logout uid as the same one created in FIRAuth.auth()?.createUserWithEmail 我也有一个注销场景,当我按注销按钮时,我得到的注销uid与在FIRAuth.auth()?. createUserWithEmail中创建的相同。

Any ideas why I have 2 different uid's? 任何想法为什么我有2个不同的uid? This seems to be my crash issues. 这似乎是我的崩溃问题。

AppDelegate AppDelegate

import UIKit
import Firebase
import FirebaseAuth
import FirebaseDatabase
import FirebaseStorage
import GoogleMaps

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    override init() {
        super.init()

        //Configure App for FireBase
        FIRApp.configure()

        //Firebase App Offline Updates
        FIRDatabase.database().persistenceEnabled = true

        GMSServices.provideAPIKey("mykey")
    }//end override init


func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

        let myUserID = FIRAuth.auth()?.currentUser?.uid

        let connectedRef = FIRDatabase.database().referenceWithPath(".info/connected")
        connectedRef.observeEventType(.Value, withBlock: { 
                    (connected) in

        if let boolean = connected.value as? Bool where boolean == true {
                print("\nApp Delegate: Firebase is connected")

                if myUserID != nil{
                //This uid is different from the one created in signUp but yet it is what's shown in the Database but not Auth
                print("App Delegate: UID is \(myUserID!)\n")
                }
            } else {
                print("\nApp Delegate: Firebase is NOT connected\n")
            }
        })

self.window?.makeKeyAndVisible()

        return true
    }

SignUpController 注册控制器

import UIKit
import Firebase
import FirebaseAuth
import FirebaseDatabase
import FirebaseCrash

class SignUpController: UIViewController {

@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!

var dbRef: FIRDatabaseReference!
let myUserID = FIRAuth.auth()?.currentUser?.uid


override func viewDidLoad() {
      super.viewDidLoad()
self.dbRef = FIRDatabase.database().reference()
}

@IBAction func signUpButton(sender: UIButton) {

FIRAuth.auth()?.createUserWithEmail(self.emailTextField.text!, password: self.passwordTextField.text!, completion: {

            (user, err) in

//This uid is different from AppDelegate but is what is shown in Auth but not in Database
print("\nSignUp: UID is \(user!uid)\n")
print("Now Look at the UID printed from the above property myUserID: \(self.myUserID)")

if err != nil{
        print((error?.localizedDescription)\n)
       }

let usersRef = self.dbRef.child("users")
let userIDRef = usersRef.child(self.myUserID!)
let userEmailRef = userIDRef.child("userEmailRef")

let email = self.self.emailTextField.text!
let dict = [String:AnyObject]()
dict.updateValue(email, forKey: "emailKey")
dict.updateValue(self.myUserID!, forKey: "userIDKey")

userEmailRef.updateChildValues(dict, withCompletionBlock: {

                (error, user) in

                if error != nil{
                    print(err?.localizedDescription\n")
                }
     })
   })
 }
}

LogoOutController LogoOutController

import UIKit
import Firebase
import FirebaseAuth
import FirebaseDatabase
import FirebaseCrash

class LogoutController: UIViewController {

var dbRef: FIRDatabaseReference!
let myUserID = FIRAuth.auth()?.currentUser?.uid


override func viewDidLoad() {
      super.viewDidLoad()
self.dbRef = FIRDatabase.database().reference()
}


@IBAction func signUpButton(sender: UIButton) {

try! FIRAuth.auth()!.signOut()

print("\nLogout: UID is \(self.myUserID!)")

  }
}

You're asking firebase for a uid in the app delegate without checking if a user is logged in. It may be assigning a temporary/anonymous account to the user until they create an account. 您在应用程序委托中向Firebase询问uid,而无需检查用户是否已登录。它可能正在为用户分配一个临时/匿名帐户,直到他们创建一个帐户为止。 Check the "Auth" settings in the firebase console and see if multiple accounts are being created in the process. 在Firebase控制台中检查“身份验证”设置,然后查看在此过程中是否正在创建多个帐户。

Remove the code from the App Delegate and move "let myUserID = FIRAuth.auth()?.currentUser?.uid" into the 'createUserWithEmail' function in the signup controller 从应用程序代理中删除代码,然后将“ let myUserID = FIRAuth.auth()?. currentUser?.uid”移至注册控制器中的“ createUserWithEmail”函数中

Problem solved. 问题解决了。 Here's the new code via @Justin Doan 's accepted answer 这是通过@Justin Doan接受的答案的新代码

AppDelegate AppDelegate

import UIKit
import Firebase
import FirebaseAuth
import FirebaseDatabase
import FirebaseStorage
import GoogleMaps

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    override init() {
        super.init()

        //Configure App for FireBase
        FIRApp.configure()

        //Firebase App Offline Updates
        FIRDatabase.database().persistenceEnabled = true

        GMSServices.provideAPIKey("mykey")
    }//end override init


func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

        let connectedRef = FIRDatabase.database().referenceWithPath(".info/connected")
        connectedRef.observeEventType(.Value, withBlock: { 
                    (connected) in

        if let boolean = connected.value as? Bool where boolean == true {
                print("\nApp Delegate: Firebase is connected")
            } else {
                print("\nApp Delegate: Firebase is NOT connected\n")
            }
        })

self.window?.makeKeyAndVisible()

        return true
    }

SignUpController 注册控制器

import UIKit
import Firebase
import FirebaseAuth
import FirebaseDatabase
import FirebaseCrash

class SignUpController: UIViewController {

@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!

var dbRef: FIRDatabaseReference!

override func viewDidLoad() {
      super.viewDidLoad()
self.dbRef = FIRDatabase.database().reference()
}

@IBAction func signUpButton(sender: UIButton) {

FIRAuth.auth()?.createUserWithEmail(self.emailTextField.text!, password: self.passwordTextField.text!, completion: {

            (user, err) in

let myUserID = FIRAuth.auth()?.currentUser?.uid

//This should always print a successful match
if user!.uid != currentUserID{
            print("\nYOUR USER ID'S DON'T MATCH")
        }else{
            print("\nTHE USER ID's SUCCESSFULLY MATCH")
        }

if err != nil{
        print((error?.localizedDescription)\n)
       }

let usersRef = self.dbRef.child("users")
let userIDRef = usersRef.child(self.myUserID!)
let userEmailRef = userIDRef.child("userEmailRef")

let email = self.self.emailTextField.text!
let dict = [String:AnyObject]()
dict.updateValue(email, forKey: "emailKey")
dict.updateValue(self.myUserID!, forKey: "userIDKey")

userEmailRef.updateChildValues(dict, withCompletionBlock: {

                (error, user) in

                if error != nil{
                    print(err?.localizedDescription\n")
                }
     })
   })
 }
}

There's no change to LogoutController LogoutController没有变化

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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