Firebase Database is Overwriting Data after the Google and Facebook Authentication
up vote
-1
down vote
favorite
I am creating an application that will utilizes the login SDKs of Google and Facebook for iOS development. I have succeeded in connecting and authorizing these accounts my Firebase Authentication section. I would like to store these users in the database in order to use this information in different controllers throughout the application. I cannot seem to check if there is a user email and user ID that matches and if so I would like to add another User node and not overwrite one that is already there.

Here Are My Controllers
Google Sign In:
`
import UIKit
import CoreData
import Firebase
import FBSDKCoreKit
import GoogleSignIn
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, GIDSignInDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
FirebaseApp.configure()
GIDSignIn.sharedInstance()?.clientID = FirebaseApp.app()?.options.clientID
GIDSignIn.sharedInstance()?.delegate = self
FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
return true
}
@available(iOS 9.0, *)
func application(_ application: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
return GIDSignIn.sharedInstance().handle(url, sourceApplication:options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String, annotation: [:])
let handled: Bool = FBSDKApplicationDelegate.sharedInstance().application(application, open: url, sourceApplication: options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String, annotation: options[UIApplication.OpenURLOptionsKey.annotation])
// Add any custom logic here.
return handled
}
func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
if let error = error {
print("Failed to log into Google: ", error)
return
}
guard let authentication = user.authentication else {return}
let credential = GoogleAuthProvider.credential(withIDToken: authentication.idToken, accessToken: authentication.accessToken)
Auth.auth().signInAndRetrieveData(with: credential) { (authResult, error) in
let currentUserID = Auth.auth().currentUser?.uid
let email = Auth.auth().currentUser?.email
let ref = Database.database().reference()
if let error = error {
print("Failed to create Firebase User with Google: ", error)
return
}
print("Successful creation of Firebase User with Google")
ref.child("Users").child("User ID").setValue(currentUserID)
ref.child("Users").child("User Email").setValue(email)
}
print("Successful log in with Google:", user)
}
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:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "AggieAchieve")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error (error), (error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error (nserror), (nserror.userInfo)")
}
}
}
}
`
Facebook Sign In:`
import UIKit
import FBSDKCoreKit
import FBSDKLoginKit
import Firebase
import GoogleSignIn
class LoginViewController: UIViewController, FBSDKLoginButtonDelegate, GIDSignInUIDelegate {
/*What to Load on App-Startup*/
override func viewDidLoad() {
super.viewDidLoad()
setupLoginViews()
GIDSignIn.sharedInstance().uiDelegate = self
}
/*Elements added to Login View*/
fileprivate func setupLoginViews() {
view.addSubview(googleSignInButton)
view.addSubview(facebookSignInButton)
googleSignInButton.anchor(view.safeAreaLayoutGuide.topAnchor, left: view.safeAreaLayoutGuide.leftAnchor, bottom: nil, right: view.safeAreaLayoutGuide.rightAnchor, topConstant: 600, leftConstant: 16, bottomConstant: 0, rightConstant: 16, widthConstant: 0, heightConstant: 50)
facebookSignInButton.anchor(view.safeAreaLayoutGuide.topAnchor, left: view.safeAreaLayoutGuide.leftAnchor, bottom: nil, right: view.safeAreaLayoutGuide.rightAnchor, topConstant: 670, leftConstant: 16, bottomConstant: 0, rightConstant: 16, widthConstant: 0, heightConstant: 50)
}
/*Facebook Button*/
lazy var facebookSignInButton: UIButton = {
let buttonImage = UIImage(named: "icons8-facebook-16")
var button = UIButton(type: .system)
button.setTitle("Login with Facebook", for: .normal)
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: Service.buttonTitleFontSize)
button.setTitleColor(Service.buttonTitleColor, for: .normal)
button.backgroundColor = Service.buttonBackgroundColorFacebookSignIn
button.layer.masksToBounds = true
button.layer.cornerRadius = Service.buttonCornerRadius
button.setImage(buttonImage?.withRenderingMode(.alwaysTemplate), for: .normal)
button.tintColor = .white
button.contentMode = .scaleAspectFit
button.addTarget(self, action: #selector(handleFacebookSignInButtonTapped), for: .touchUpInside)
return button
}()
/*Google Button*/
lazy var googleSignInButton: UIButton = {
let buttonImage = UIImage(named: "icons8-google-48")
var button = UIButton(type: .system)
button.setTitle("Login with Google", for: .normal)
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: Service.buttonTitleFontSize)
button.setTitleColor(Service.buttonTitleColor, for: .normal)
button.backgroundColor = Service.buttonBacgroundColorGoogleSignIn
button.layer.masksToBounds = true
button.layer.cornerRadius = Service.buttonCornerRadius
button.setImage(buttonImage?.withRenderingMode(.alwaysTemplate), for: .normal)
button.tintColor = .white
button.contentMode = .scaleAspectFit
button.addTarget(self, action: #selector(handleGoogleSignInButtonTapped), for: .touchUpInside)
return button
}()
/*Method to Run after Google Sign in is Chosen*/
@objc func handleGoogleSignInButtonTapped() {
GIDSignIn.sharedInstance().signIn()
self.performSegue(withIdentifier: "GoogleSegue", sender: self)
}
/*Method to Run after Facebook Sign in is Chosen*/
@objc func handleFacebookSignInButtonTapped() {
FBSDKLoginManager().logIn(withReadPermissions: ["email", "public_profile"], from: self) { (FBSDKLoginManagerLoginResult, error) in
if error != nil {
print ("Facebook Login Failed:", error)
return
}
self.showEmailAddress()
}
}
func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {
if error != nil {
print(error)
return
}
self.showEmailAddress()
}
func loginButtonDidLogOut(_ loginButton: FBSDKLoginButton!) {
print("Logged out of Facebook")
}
/*Facebook Authorization & Graph Request*/
func showEmailAddress() {
let credential = FacebookAuthProvider.credential(withAccessToken: FBSDKAccessToken.current().tokenString)
Auth.auth().signInAndRetrieveData(with: credential) { (AuthDataResult, error) in
if error != nil {
print("Something went wrong with our Facebook User: ", error)
return
}
print("Successfuly logged in with our Facebook User: ", AuthDataResult)
self.performSegue(withIdentifier: "FacebookSegue", sender: self)
}
FBSDKGraphRequest(graphPath: "/me", parameters: ["fields": "id, name, email"]).start {
(connection, graphResult, error) in
if error != nil {
print("Failed to Start Graph Request:", error)
return
}
print(graphResult)
}
}
} /*EOF*/
`
Any help would be greatly appreciated.
ios swift
add a comment |
up vote
-1
down vote
favorite
I am creating an application that will utilizes the login SDKs of Google and Facebook for iOS development. I have succeeded in connecting and authorizing these accounts my Firebase Authentication section. I would like to store these users in the database in order to use this information in different controllers throughout the application. I cannot seem to check if there is a user email and user ID that matches and if so I would like to add another User node and not overwrite one that is already there.

Here Are My Controllers
Google Sign In:
`
import UIKit
import CoreData
import Firebase
import FBSDKCoreKit
import GoogleSignIn
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, GIDSignInDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
FirebaseApp.configure()
GIDSignIn.sharedInstance()?.clientID = FirebaseApp.app()?.options.clientID
GIDSignIn.sharedInstance()?.delegate = self
FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
return true
}
@available(iOS 9.0, *)
func application(_ application: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
return GIDSignIn.sharedInstance().handle(url, sourceApplication:options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String, annotation: [:])
let handled: Bool = FBSDKApplicationDelegate.sharedInstance().application(application, open: url, sourceApplication: options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String, annotation: options[UIApplication.OpenURLOptionsKey.annotation])
// Add any custom logic here.
return handled
}
func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
if let error = error {
print("Failed to log into Google: ", error)
return
}
guard let authentication = user.authentication else {return}
let credential = GoogleAuthProvider.credential(withIDToken: authentication.idToken, accessToken: authentication.accessToken)
Auth.auth().signInAndRetrieveData(with: credential) { (authResult, error) in
let currentUserID = Auth.auth().currentUser?.uid
let email = Auth.auth().currentUser?.email
let ref = Database.database().reference()
if let error = error {
print("Failed to create Firebase User with Google: ", error)
return
}
print("Successful creation of Firebase User with Google")
ref.child("Users").child("User ID").setValue(currentUserID)
ref.child("Users").child("User Email").setValue(email)
}
print("Successful log in with Google:", user)
}
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:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "AggieAchieve")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error (error), (error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error (nserror), (nserror.userInfo)")
}
}
}
}
`
Facebook Sign In:`
import UIKit
import FBSDKCoreKit
import FBSDKLoginKit
import Firebase
import GoogleSignIn
class LoginViewController: UIViewController, FBSDKLoginButtonDelegate, GIDSignInUIDelegate {
/*What to Load on App-Startup*/
override func viewDidLoad() {
super.viewDidLoad()
setupLoginViews()
GIDSignIn.sharedInstance().uiDelegate = self
}
/*Elements added to Login View*/
fileprivate func setupLoginViews() {
view.addSubview(googleSignInButton)
view.addSubview(facebookSignInButton)
googleSignInButton.anchor(view.safeAreaLayoutGuide.topAnchor, left: view.safeAreaLayoutGuide.leftAnchor, bottom: nil, right: view.safeAreaLayoutGuide.rightAnchor, topConstant: 600, leftConstant: 16, bottomConstant: 0, rightConstant: 16, widthConstant: 0, heightConstant: 50)
facebookSignInButton.anchor(view.safeAreaLayoutGuide.topAnchor, left: view.safeAreaLayoutGuide.leftAnchor, bottom: nil, right: view.safeAreaLayoutGuide.rightAnchor, topConstant: 670, leftConstant: 16, bottomConstant: 0, rightConstant: 16, widthConstant: 0, heightConstant: 50)
}
/*Facebook Button*/
lazy var facebookSignInButton: UIButton = {
let buttonImage = UIImage(named: "icons8-facebook-16")
var button = UIButton(type: .system)
button.setTitle("Login with Facebook", for: .normal)
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: Service.buttonTitleFontSize)
button.setTitleColor(Service.buttonTitleColor, for: .normal)
button.backgroundColor = Service.buttonBackgroundColorFacebookSignIn
button.layer.masksToBounds = true
button.layer.cornerRadius = Service.buttonCornerRadius
button.setImage(buttonImage?.withRenderingMode(.alwaysTemplate), for: .normal)
button.tintColor = .white
button.contentMode = .scaleAspectFit
button.addTarget(self, action: #selector(handleFacebookSignInButtonTapped), for: .touchUpInside)
return button
}()
/*Google Button*/
lazy var googleSignInButton: UIButton = {
let buttonImage = UIImage(named: "icons8-google-48")
var button = UIButton(type: .system)
button.setTitle("Login with Google", for: .normal)
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: Service.buttonTitleFontSize)
button.setTitleColor(Service.buttonTitleColor, for: .normal)
button.backgroundColor = Service.buttonBacgroundColorGoogleSignIn
button.layer.masksToBounds = true
button.layer.cornerRadius = Service.buttonCornerRadius
button.setImage(buttonImage?.withRenderingMode(.alwaysTemplate), for: .normal)
button.tintColor = .white
button.contentMode = .scaleAspectFit
button.addTarget(self, action: #selector(handleGoogleSignInButtonTapped), for: .touchUpInside)
return button
}()
/*Method to Run after Google Sign in is Chosen*/
@objc func handleGoogleSignInButtonTapped() {
GIDSignIn.sharedInstance().signIn()
self.performSegue(withIdentifier: "GoogleSegue", sender: self)
}
/*Method to Run after Facebook Sign in is Chosen*/
@objc func handleFacebookSignInButtonTapped() {
FBSDKLoginManager().logIn(withReadPermissions: ["email", "public_profile"], from: self) { (FBSDKLoginManagerLoginResult, error) in
if error != nil {
print ("Facebook Login Failed:", error)
return
}
self.showEmailAddress()
}
}
func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {
if error != nil {
print(error)
return
}
self.showEmailAddress()
}
func loginButtonDidLogOut(_ loginButton: FBSDKLoginButton!) {
print("Logged out of Facebook")
}
/*Facebook Authorization & Graph Request*/
func showEmailAddress() {
let credential = FacebookAuthProvider.credential(withAccessToken: FBSDKAccessToken.current().tokenString)
Auth.auth().signInAndRetrieveData(with: credential) { (AuthDataResult, error) in
if error != nil {
print("Something went wrong with our Facebook User: ", error)
return
}
print("Successfuly logged in with our Facebook User: ", AuthDataResult)
self.performSegue(withIdentifier: "FacebookSegue", sender: self)
}
FBSDKGraphRequest(graphPath: "/me", parameters: ["fields": "id, name, email"]).start {
(connection, graphResult, error) in
if error != nil {
print("Failed to Start Graph Request:", error)
return
}
print(graphResult)
}
}
} /*EOF*/
`
Any help would be greatly appreciated.
ios swift
add a comment |
up vote
-1
down vote
favorite
up vote
-1
down vote
favorite
I am creating an application that will utilizes the login SDKs of Google and Facebook for iOS development. I have succeeded in connecting and authorizing these accounts my Firebase Authentication section. I would like to store these users in the database in order to use this information in different controllers throughout the application. I cannot seem to check if there is a user email and user ID that matches and if so I would like to add another User node and not overwrite one that is already there.

Here Are My Controllers
Google Sign In:
`
import UIKit
import CoreData
import Firebase
import FBSDKCoreKit
import GoogleSignIn
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, GIDSignInDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
FirebaseApp.configure()
GIDSignIn.sharedInstance()?.clientID = FirebaseApp.app()?.options.clientID
GIDSignIn.sharedInstance()?.delegate = self
FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
return true
}
@available(iOS 9.0, *)
func application(_ application: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
return GIDSignIn.sharedInstance().handle(url, sourceApplication:options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String, annotation: [:])
let handled: Bool = FBSDKApplicationDelegate.sharedInstance().application(application, open: url, sourceApplication: options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String, annotation: options[UIApplication.OpenURLOptionsKey.annotation])
// Add any custom logic here.
return handled
}
func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
if let error = error {
print("Failed to log into Google: ", error)
return
}
guard let authentication = user.authentication else {return}
let credential = GoogleAuthProvider.credential(withIDToken: authentication.idToken, accessToken: authentication.accessToken)
Auth.auth().signInAndRetrieveData(with: credential) { (authResult, error) in
let currentUserID = Auth.auth().currentUser?.uid
let email = Auth.auth().currentUser?.email
let ref = Database.database().reference()
if let error = error {
print("Failed to create Firebase User with Google: ", error)
return
}
print("Successful creation of Firebase User with Google")
ref.child("Users").child("User ID").setValue(currentUserID)
ref.child("Users").child("User Email").setValue(email)
}
print("Successful log in with Google:", user)
}
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:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "AggieAchieve")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error (error), (error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error (nserror), (nserror.userInfo)")
}
}
}
}
`
Facebook Sign In:`
import UIKit
import FBSDKCoreKit
import FBSDKLoginKit
import Firebase
import GoogleSignIn
class LoginViewController: UIViewController, FBSDKLoginButtonDelegate, GIDSignInUIDelegate {
/*What to Load on App-Startup*/
override func viewDidLoad() {
super.viewDidLoad()
setupLoginViews()
GIDSignIn.sharedInstance().uiDelegate = self
}
/*Elements added to Login View*/
fileprivate func setupLoginViews() {
view.addSubview(googleSignInButton)
view.addSubview(facebookSignInButton)
googleSignInButton.anchor(view.safeAreaLayoutGuide.topAnchor, left: view.safeAreaLayoutGuide.leftAnchor, bottom: nil, right: view.safeAreaLayoutGuide.rightAnchor, topConstant: 600, leftConstant: 16, bottomConstant: 0, rightConstant: 16, widthConstant: 0, heightConstant: 50)
facebookSignInButton.anchor(view.safeAreaLayoutGuide.topAnchor, left: view.safeAreaLayoutGuide.leftAnchor, bottom: nil, right: view.safeAreaLayoutGuide.rightAnchor, topConstant: 670, leftConstant: 16, bottomConstant: 0, rightConstant: 16, widthConstant: 0, heightConstant: 50)
}
/*Facebook Button*/
lazy var facebookSignInButton: UIButton = {
let buttonImage = UIImage(named: "icons8-facebook-16")
var button = UIButton(type: .system)
button.setTitle("Login with Facebook", for: .normal)
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: Service.buttonTitleFontSize)
button.setTitleColor(Service.buttonTitleColor, for: .normal)
button.backgroundColor = Service.buttonBackgroundColorFacebookSignIn
button.layer.masksToBounds = true
button.layer.cornerRadius = Service.buttonCornerRadius
button.setImage(buttonImage?.withRenderingMode(.alwaysTemplate), for: .normal)
button.tintColor = .white
button.contentMode = .scaleAspectFit
button.addTarget(self, action: #selector(handleFacebookSignInButtonTapped), for: .touchUpInside)
return button
}()
/*Google Button*/
lazy var googleSignInButton: UIButton = {
let buttonImage = UIImage(named: "icons8-google-48")
var button = UIButton(type: .system)
button.setTitle("Login with Google", for: .normal)
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: Service.buttonTitleFontSize)
button.setTitleColor(Service.buttonTitleColor, for: .normal)
button.backgroundColor = Service.buttonBacgroundColorGoogleSignIn
button.layer.masksToBounds = true
button.layer.cornerRadius = Service.buttonCornerRadius
button.setImage(buttonImage?.withRenderingMode(.alwaysTemplate), for: .normal)
button.tintColor = .white
button.contentMode = .scaleAspectFit
button.addTarget(self, action: #selector(handleGoogleSignInButtonTapped), for: .touchUpInside)
return button
}()
/*Method to Run after Google Sign in is Chosen*/
@objc func handleGoogleSignInButtonTapped() {
GIDSignIn.sharedInstance().signIn()
self.performSegue(withIdentifier: "GoogleSegue", sender: self)
}
/*Method to Run after Facebook Sign in is Chosen*/
@objc func handleFacebookSignInButtonTapped() {
FBSDKLoginManager().logIn(withReadPermissions: ["email", "public_profile"], from: self) { (FBSDKLoginManagerLoginResult, error) in
if error != nil {
print ("Facebook Login Failed:", error)
return
}
self.showEmailAddress()
}
}
func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {
if error != nil {
print(error)
return
}
self.showEmailAddress()
}
func loginButtonDidLogOut(_ loginButton: FBSDKLoginButton!) {
print("Logged out of Facebook")
}
/*Facebook Authorization & Graph Request*/
func showEmailAddress() {
let credential = FacebookAuthProvider.credential(withAccessToken: FBSDKAccessToken.current().tokenString)
Auth.auth().signInAndRetrieveData(with: credential) { (AuthDataResult, error) in
if error != nil {
print("Something went wrong with our Facebook User: ", error)
return
}
print("Successfuly logged in with our Facebook User: ", AuthDataResult)
self.performSegue(withIdentifier: "FacebookSegue", sender: self)
}
FBSDKGraphRequest(graphPath: "/me", parameters: ["fields": "id, name, email"]).start {
(connection, graphResult, error) in
if error != nil {
print("Failed to Start Graph Request:", error)
return
}
print(graphResult)
}
}
} /*EOF*/
`
Any help would be greatly appreciated.
ios swift
I am creating an application that will utilizes the login SDKs of Google and Facebook for iOS development. I have succeeded in connecting and authorizing these accounts my Firebase Authentication section. I would like to store these users in the database in order to use this information in different controllers throughout the application. I cannot seem to check if there is a user email and user ID that matches and if so I would like to add another User node and not overwrite one that is already there.

Here Are My Controllers
Google Sign In:
`
import UIKit
import CoreData
import Firebase
import FBSDKCoreKit
import GoogleSignIn
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, GIDSignInDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
FirebaseApp.configure()
GIDSignIn.sharedInstance()?.clientID = FirebaseApp.app()?.options.clientID
GIDSignIn.sharedInstance()?.delegate = self
FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
return true
}
@available(iOS 9.0, *)
func application(_ application: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
return GIDSignIn.sharedInstance().handle(url, sourceApplication:options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String, annotation: [:])
let handled: Bool = FBSDKApplicationDelegate.sharedInstance().application(application, open: url, sourceApplication: options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String, annotation: options[UIApplication.OpenURLOptionsKey.annotation])
// Add any custom logic here.
return handled
}
func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
if let error = error {
print("Failed to log into Google: ", error)
return
}
guard let authentication = user.authentication else {return}
let credential = GoogleAuthProvider.credential(withIDToken: authentication.idToken, accessToken: authentication.accessToken)
Auth.auth().signInAndRetrieveData(with: credential) { (authResult, error) in
let currentUserID = Auth.auth().currentUser?.uid
let email = Auth.auth().currentUser?.email
let ref = Database.database().reference()
if let error = error {
print("Failed to create Firebase User with Google: ", error)
return
}
print("Successful creation of Firebase User with Google")
ref.child("Users").child("User ID").setValue(currentUserID)
ref.child("Users").child("User Email").setValue(email)
}
print("Successful log in with Google:", user)
}
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:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "AggieAchieve")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error (error), (error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error (nserror), (nserror.userInfo)")
}
}
}
}
`
Facebook Sign In:`
import UIKit
import FBSDKCoreKit
import FBSDKLoginKit
import Firebase
import GoogleSignIn
class LoginViewController: UIViewController, FBSDKLoginButtonDelegate, GIDSignInUIDelegate {
/*What to Load on App-Startup*/
override func viewDidLoad() {
super.viewDidLoad()
setupLoginViews()
GIDSignIn.sharedInstance().uiDelegate = self
}
/*Elements added to Login View*/
fileprivate func setupLoginViews() {
view.addSubview(googleSignInButton)
view.addSubview(facebookSignInButton)
googleSignInButton.anchor(view.safeAreaLayoutGuide.topAnchor, left: view.safeAreaLayoutGuide.leftAnchor, bottom: nil, right: view.safeAreaLayoutGuide.rightAnchor, topConstant: 600, leftConstant: 16, bottomConstant: 0, rightConstant: 16, widthConstant: 0, heightConstant: 50)
facebookSignInButton.anchor(view.safeAreaLayoutGuide.topAnchor, left: view.safeAreaLayoutGuide.leftAnchor, bottom: nil, right: view.safeAreaLayoutGuide.rightAnchor, topConstant: 670, leftConstant: 16, bottomConstant: 0, rightConstant: 16, widthConstant: 0, heightConstant: 50)
}
/*Facebook Button*/
lazy var facebookSignInButton: UIButton = {
let buttonImage = UIImage(named: "icons8-facebook-16")
var button = UIButton(type: .system)
button.setTitle("Login with Facebook", for: .normal)
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: Service.buttonTitleFontSize)
button.setTitleColor(Service.buttonTitleColor, for: .normal)
button.backgroundColor = Service.buttonBackgroundColorFacebookSignIn
button.layer.masksToBounds = true
button.layer.cornerRadius = Service.buttonCornerRadius
button.setImage(buttonImage?.withRenderingMode(.alwaysTemplate), for: .normal)
button.tintColor = .white
button.contentMode = .scaleAspectFit
button.addTarget(self, action: #selector(handleFacebookSignInButtonTapped), for: .touchUpInside)
return button
}()
/*Google Button*/
lazy var googleSignInButton: UIButton = {
let buttonImage = UIImage(named: "icons8-google-48")
var button = UIButton(type: .system)
button.setTitle("Login with Google", for: .normal)
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: Service.buttonTitleFontSize)
button.setTitleColor(Service.buttonTitleColor, for: .normal)
button.backgroundColor = Service.buttonBacgroundColorGoogleSignIn
button.layer.masksToBounds = true
button.layer.cornerRadius = Service.buttonCornerRadius
button.setImage(buttonImage?.withRenderingMode(.alwaysTemplate), for: .normal)
button.tintColor = .white
button.contentMode = .scaleAspectFit
button.addTarget(self, action: #selector(handleGoogleSignInButtonTapped), for: .touchUpInside)
return button
}()
/*Method to Run after Google Sign in is Chosen*/
@objc func handleGoogleSignInButtonTapped() {
GIDSignIn.sharedInstance().signIn()
self.performSegue(withIdentifier: "GoogleSegue", sender: self)
}
/*Method to Run after Facebook Sign in is Chosen*/
@objc func handleFacebookSignInButtonTapped() {
FBSDKLoginManager().logIn(withReadPermissions: ["email", "public_profile"], from: self) { (FBSDKLoginManagerLoginResult, error) in
if error != nil {
print ("Facebook Login Failed:", error)
return
}
self.showEmailAddress()
}
}
func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {
if error != nil {
print(error)
return
}
self.showEmailAddress()
}
func loginButtonDidLogOut(_ loginButton: FBSDKLoginButton!) {
print("Logged out of Facebook")
}
/*Facebook Authorization & Graph Request*/
func showEmailAddress() {
let credential = FacebookAuthProvider.credential(withAccessToken: FBSDKAccessToken.current().tokenString)
Auth.auth().signInAndRetrieveData(with: credential) { (AuthDataResult, error) in
if error != nil {
print("Something went wrong with our Facebook User: ", error)
return
}
print("Successfuly logged in with our Facebook User: ", AuthDataResult)
self.performSegue(withIdentifier: "FacebookSegue", sender: self)
}
FBSDKGraphRequest(graphPath: "/me", parameters: ["fields": "id, name, email"]).start {
(connection, graphResult, error) in
if error != nil {
print("Failed to Start Graph Request:", error)
return
}
print(graphResult)
}
}
} /*EOF*/
`
Any help would be greatly appreciated.
ios swift
ios swift
edited Nov 12 at 11:49
KENdi
5,6992821
5,6992821
asked Nov 11 at 22:14
JReddick
11
11
add a comment |
add a comment |
active
oldest
votes
active
oldest
votes
active
oldest
votes
active
oldest
votes
active
oldest
votes
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53253775%2ffirebase-database-is-overwriting-data-after-the-google-and-facebook-authenticati%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown