如何知道用户是注册还是使用Facebook和Firebase登录

0 authentication facebook ios swift firebase-authentication

我发现很难将登录逻辑与注册逻辑分开,因为firebase只有一种方法可以通过Facebook验证用户:signIn(with: AuthCredential).这一种方法将登录现有用户,或者如果它们尚不存在则自动注册,因此我无法知道用户是否第一次注册,因此我可以保留其他信息firebase数据库中的用户.

非常感谢任何帮助解决这个问题.我的应用程序是用Swift编写的,所以任何带代码的解决方案在Swift中都会有所帮助.谢谢

查看回调内的评论

private func rx_firebaseLogin(with credential: AuthCredential, userInfo: [String: AnyObject]) -> Observable<[String: AnyObject]> {

    return Observable<[String: AnyObject]>.create { observable in

        Auth.auth().signIn(with: credential) { (user, error) in

            // IF user is already authenticated, User will get signed in automatically. 
            // IF user is new, that user will automatically get signed up. 
            // So I cannot put code here to save user info in db because I could potentially just be signing in a user, and end up duplicating a pre-existing user.

            guard error == nil else {
                observable.onError(AuthError.custom(message: error!.localizedDescription))
                print(error!.localizedDescription)
                return
            }

            guard user != nil else {
                observable.onError(AuthError.invalidFirebaseUser)
                print("debugger: error logging user")
                return
            }

            var data = userInfo
            data[Constant.id] = user!.uid as AnyObject

            observable.onNext(data)
            observable.onCompleted()
        }
        return Disposables.create()
    }
}
Run Code Online (Sandbox Code Playgroud)

kev*_*rly 7

如果您使用的是Firebase的数据库,我假设您在那里存储有关该用户的信息.授权用户时,请检查该用户是否在您的数据库中.如果不是,那是他们第一次注册.这是我做的:

let accessToken = FBSDKAccessToken.current()
guard let accessTokenString = accessToken?.tokenString else {return}

let credentials = FacebookAuthProvider.credential(withAccessToken: accessTokenString)

Auth.auth().signIn(with: credentials, completion: { (user, error) in
    let id = Auth.auth().currentUser?.uid
    let ref = Database.database().reference(withPath: "users")

    ref.child(id).observeSingleEvent(of: .value, with: {(snapshot) in
        if snapshot.exists() {
            //User is signing IN
        } else {
            //User is signing UP
        }
    } 
}
Run Code Online (Sandbox Code Playgroud)

假设数据库结构:

  • 用户
    • uniqueUserId