Skip to content

Instantly share code, notes, and snippets.

@RealEmmettS
Created March 24, 2022 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RealEmmettS/e45fe98713336f34b6a4178872b10208 to your computer and use it in GitHub Desktop.
Save RealEmmettS/e45fe98713336f34b6a4178872b10208 to your computer and use it in GitHub Desktop.
import Firebase
import FirebaseFirestore
import FirebaseAuth
import FirebaseAuthUI
import FirebaseFacebookAuthUI
import FirebaseGoogleAuthUI
import FirebaseOAuthUI
import FirebasePhoneAuthUI
import FirebaseEmailAuthUI
//class ViewController: UIViewController, FUIAuthDelegate
//MARK: Manually Retrieve Data
///This method IS NOT listening for data changes on the server, and it only runs when explicitly called
let docRef = db.collection(userID).document("DOCNAME")
docRef.getDocument { (document, error) in
if let document = document, document.exists {
let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
print("Document data: \(dataDescription)")
let data = document.data()!
if data["VALUENAME"] != nil{
//code goes here
}
if data["VALUENAME_2"] != nil{
//code goes here
}else{
print("\n\n\nno value found\n\n\n")
//code goes here
}
} else {
print("Document does not exist")
}
}
//MARK: Auto-Retrieve Data
///This method is constantly listening for data changes on the server, and will run automatically whenever new data is found
db.collection(userID).document("DOCNAME")
.addSnapshotListener { documentSnapshot, error in
guard let document = documentSnapshot else {
print("Error fetching document: \(error!)")
return
}
guard let data = document.data() else {
print("Document data was empty.")
//code goes here
return
}
print("Current data: \(data)")
//someLocalVariable = "\(data["VALUENAME"] ?? "name")"
//code goes here
}
//MARK: -User Stuff (sign in/out)
//MARK: viewDidAppear
override func viewDidAppear(_ animated: Bool) {
if didSignOut == true{
signOutWithFirebase()
didSignOut = false
}
if isUserSignedIn() {
//userName = getData(documentName: "userInfo")
performSegue(withIdentifier: "movePastSignIn", sender: nil)
}
}
@IBAction func pressed(_ sender: Any) {
print("\n\n\nPresenting AuthUI\n\n\n")
let authUI = FUIAuth.defaultAuthUI()
authUI!.delegate = self
let providers: [FUIAuthProvider] = [
FUIEmailAuth(),
// FUIGoogleAuth(),
// FUIFacebookAuth(),
// FUITwitterAuth(),
// FUIPhoneAuth(authUI:FUIAuth.defaultAuthUI()),
]
authUI!.providers = providers
let authViewController = authUI!.authViewController()
present(authViewController, animated: true, completion: nil)
}
func authUI(_ authUI: FUIAuth, didSignInWith user: User?, error: Error?) {
if error == nil{
print("\n\n –– success –– \n\n")
//userName = getData(documentName: "userInfo")
guard let user = Auth.auth().currentUser else {return}
userID = user.uid
performSegue(withIdentifier: "movePastSignIn", sender: nil)
}else{
print("\n\n –– error –– \n\n")
}
// switch error{
// case nil:
// print("\n\n –– success –– \n\n")
// default:
// print("\n\n –– error –– \n\n")
// }
}
func isUserSignedIn() -> Bool{
if Auth.auth().currentUser != nil {
// User is signed in.
let user = Auth.auth().currentUser
if let user = user {
// The user's ID, unique to the Firebase project.
// Do NOT use this value to authenticate with your backend server,
// if you have one. Use getTokenWithCompletion:completion: instead.
let uid = user.uid
userID = uid
let email = user.email
updateUser(type: .email, value: user.email!)
let photoURL = user.photoURL
var multiFactorString = "MultiFactor: "
for info in user.multiFactor.enrolledFactors {
multiFactorString += info.displayName ?? "[DispayName]"
multiFactorString += " "
}
// ...
}
//MARK: Auto-Retrieve Account Data
db.collection(userID).document("userInfo")
.addSnapshotListener { documentSnapshot, error in
guard let document = documentSnapshot else {
print("Error fetching document: \(error!)")
return
}
guard let data = document.data() else {
print("Document data was empty.")
userName = "false"
return
}
print("Current data: \(data)")
userName = "\(data)"
}
return true
} else {
// No user is signed in.
return false
}
}
//MARK: Sign-Out Button
@IBAction func signOutPressed(_ sender: Any) {
signOutWithFirebase()
didSignOut = true
//On the next line, replace "backToSignIn" with the segue identifier that leads back to the main sign-in page
performSegue(withIdentifier: "backToSignIn", sender: self)
}
//MARK: Sign Out
func signOutWithFirebase(){
//Resetting AuthUI and its properties
let authUI = FUIAuth.defaultAuthUI()
authUI!.delegate = self
let providers: [FUIAuthProvider] = [
//3FUIGoogleAuth(),
FUIEmailAuth(),
/*FUIPhoneAuth(authUI:FUIAuth.defaultAuthUI()!),*/
]
authUI!.providers = providers
//Signing out of everything...
let firebaseAuth = Auth.auth()
do {
try authUI!.signOut()
try firebaseAuth.signOut()
userID = ""
} catch {
print("Uh-Oh")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment