Microsoft Sign-In Through Firebase - swift

I am very new to app development so please forgive me. I have researched far too long and cannot seem to understand how to code my login button for Microsoft sign-in using Firebase. Here is my code so far:
import UIKit
import FirebaseAuth
class LoginViewController: UIViewController {
var ref : DatabaseAuth!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBAction func logIntapped(_ sender: Any) {
let provider = OAuthProvider(providerID: "microsoft.com")
provider.getCredentialWith(nil) { (credential, error) in
if error != nil {
// Handle error.
print("Failed to retreive credential.")
return
}
if credential != nil {
Auth.auth().signIn(with:completion:)(<#AuthCredential#>) { authResult, error in
if error != nil {
// Handle error.
}
}
} else {
print("Credential is nil.")
}
}
}
}

You need to pass the credential that you get back from Microsoft, into your call to Firebase Authentication. So something like:
Auth.auth().signIn(with: credential) { authResult, error in
...
Also see the Firebase documentation on handling the sign-in flow with the Firebase SDK.

Related

Use of unresolved identifier 'FUIEmailAuth'FUIEmailAuth

I'm making a login screen using firebase auth UI and swift.
When I run the app, currently it only shows a welcome screen like this welcome screen.
But I want to display the page the firebase prebuilt UI with a text field that a user can type their email address, something like this. login-with email
Here is my current code.
import UIKit
import FirebaseUI
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
//MARK: - sign in / sign up
#IBAction func playPressed(_ sender: UIButton) {
let authUI = FUIAuth.defaultAuthUI()
guard authUI != nil else {
return
}
authUI?.delegate = self
authUI?.providers = [FUIEmailAuth()]
let authViewController = authUI!.authViewController()
present(authViewController, animated: true, completion: nil)
}
}
extension ViewController: FUIAuthDelegate{
func authUI(_ authUI: FUIAuth, didSignInWith authDataResult: AuthDataResult?, error: Error?) {
if error != nil {
return
}
performSegue(withIdentifier: K.loginSegue, sender: self)
}
}
and I get error on the code written as "authUI?.providers = [FUIEmailAuth()]". The error message is
Use of unresolved identifier 'FUIEmailAuth'FUIEmailAuth
I saw some other people run into the same problem, and I tried pod update, but I still get the error message.
Also, on the firebase document, they use 'FUIEmailAuth' in their sample code, so I wonder why I'm getting that error and how to fix it.
I just add pod 'FirebaseUI/Email' in my pod file and it solved the problem.

Firebase Login Persistence Swift

I'm using Firebase to handle my user register and login for my app. But if I log in, and then close my app entirely - the user is forced to re-log in. I'd like to keep the user logged in unless they click "Log out"
My login code is this:
Auth.auth().signIn(withEmail: email, password: password, completion: {(user, error) in
if let firebaseError = error {
print(firebaseError.localizedDescription)
return
}
self.presentTabBar()
})
}
}
How do I keep this user logged in unless specifically told to logout?
Here's a handy full example for 2020:
Anywhere in your iOS+Firebase app, you can simply say:
guard let uid = Auth.auth().currentUser?.uid else {
return print("no current user!")
}
Thus, on the launch screen of your app, simply:
import UIKit
import Firebase
import FirebaseUI
class ViewController: UIViewController, FUIAuthDelegate {
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
guard let uid = Auth.auth().currentUser?.uid else {
return print("no current user, hence AuthUI flow...")
basicAuthUIFlow()
}
print("User .. \(Auth.auth().currentUser?.displayName)")
continueWhenUserPresent()
}
It's that easy. So then as usual ...
private func basicAuthUIFlow() {
let authUI = FUIAuth.defaultAuthUI()
authUI?.delegate = self
let pp: [FUIAuthProvider] = [ FUIGoogleAuth() ]
authUI?.providers = pp
if let authVC = authUI?.authViewController() {
present(authVC, animated: true)
}
}
func authUI(_ authUI: FUIAuth,
didSignInWith authDataResult: AuthDataResult?,url: URL?, error: Error?) {
let u = authDataResult?.user
print("Successful login via authUI \(String(describing: u?.displayName))")
continueWhenUserPresent()
}
private func continueWhenUserPresent() {
.. pushViewController .. your first screen
}
Check if the user is logged in or not:
if Auth.auth().currentUser != nil {
// User is signed in.
// ...
} else {
// No user is signed in.
// ...
}
if the user is logged in, then go the Home ViewController. This way when he opens the app again he will go to the Home ViewController unless he sign outsFIRAuth.auth().signOut()
For more info check this: https://firebase.google.com/docs/auth/ios/manage-users
For keep user login you need to check currentUser Auth session, If it's not nil then you can redirect user to Home screen.
Call "setRootViewController" method from didFinishLaunchingWithOptions, just after FirebaseApp.configure() code
Swift 4
func setRootViewController() {
if Auth.auth().currentUser != nil {
// Set Your home view controller Here as root View Controller
self.presentTabBar()
} else {
// Set you login view controller here as root view controller
}
}

Unable to pass Facebook User properties to Firebase FIRAuth in Swift 3

I'm using the following function to login a User with a Facebook Token and the Firebase FIRAuth function. There is no error and no print of email property. As if the function wouldn't be called.
var login = FBSDKLoginManager()
#IBOutlet weak var fbBtnPressed: UIButton!
#IBAction func fbBtnPressed(_ sender: AnyObject) {
login.logIn(withReadPermissions: ["public_profile", "email", "user_friends"], from: self) { (FBSDKLoginManagerLoginResult, Error) in
if Error != nil {
print("The login with Facebook don't working. Erro: \(Error)")
} else {
let accessToken = FBSDKAccessToken.current().tokenString
print("Login with Facebook ok. \(accessToken)")
let credential = FIRFacebookAuthProvider.credential(withAccessToken: FBSDKAccessToken.current().tokenString)
FIRAuth.auth()?.signIn(with: credential) { (email, error) in
if (error != nil) {
print("The login in the Firebase broke \(error)")
} else {
print("Login in the Firebase ok \(email)")
}
}
}
}
}
After a lot of research, it seems to be a change in Swift3 in combination with the Keychain swap.
You have to enable the Keychange Sharing in your project under capabilities.

Swift 2.0 working Facebook custom login button

I beg all of thee. I searched everywhere but i can't find working swift 2.0 code for Facebook custom login button with returning Access Token. My code simply don't work. (token is not returning Facebook token)
Considering that you have done all the setup as described by the Facebook developer page, you need to do the following in your login view controller:
// Import the following on top below "import UIKit" in your login view controller
import FBSDKCoreKit
import FBSDKLoginKit
// This is your action code for your custom login button for login using facebook in Swift
#IBAction func fbLoginBtn(sender: AnyObject) {
let permisions = ["public_profile", "email"]
PFFacebookUtils.logInInBackgroundWithReadPermissions(permisions) {
(user: PFUser?, error: NSError?) -> Void in
if let error = error {
print(error)
} else {
if let user = user {
print(user)
// "yourSegue" below will be the segue identifier for your new view.
self.performSegueWithIdentifier("yourSegue", sender: self)
}
}
}
}
In case you have not setup your app at Facebook developer, please following the simple steps as mentioned in Facebook Developer Page.
1 - Add a normal button in your view then add the FB login class "FBSDKLoginButton"
2 - Declare your button in your ViewController
#IBOutlet weak var FBLoginButton: FBSDKLoginButton!
3 - Add in your ViewDidload methode
if (FBSDKAccessToken.currentAccessToken() != nil)
{
// User is already logged in, do work such as go to next view controller.
}
else
{
self.FBLoginButton.delegate = self
FBLoginButton.readPermissions = ["public_profile", "email", "user_friends"]
}
4-Add Delegate Login and logout button funcutions
func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!) {
loginButton.readPermissions = ["public_profile", "email", "user_friends"]
let fbAccessToken = FBSDKAccessToken.currentAccessToken().tokenString
FBSDKGraphRequest(graphPath: "me?fields=id,name,email,gender,first_name,last_name,middle_name,birthday&access_token=\(fbAccessToken)", parameters: nil).startWithCompletionHandler({ (connection, result, error) in
if ((error) != nil) {
// Process error
print("Error: \(error)")
} else {
print("fetched user: \(result)")
}
})
}
func loginButtonDidLogOut(loginButton: FBSDKLoginButton!) {
print("User Logged Out")
}

Swift: The supplied Facebook session token is expired or invalid

I am trying to use FacebookLogin with Parse however i am receiving an error that,
The supplied Facebook session token is expired or invalid
every time I try to login using the code below.
import Foundation
import UIKit
class LoginViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let permissions = ["public_profile", "email"]
PFFacebookUtils.logInWithPermissions(permissions) {
(user, error) in
if (user == nil) {
if (error == nil) {
println("User cancelled FB login")
}else{
println("FB login error: \(error)")
}
} else if user.isNew {
println("User signed up and logged in with Facebook")
} else {
println("User logged in via Facebook")
}
}
}
I had this error once and had to put this line before the login call in Objective-C
[FBSession.activeSession closeAndClearTokenInformation];
I can't seem to find the swift equivalent in the Parse SDK, and the Facebook SDK is still only in Objective-C.
You may have to add this line to an Objective-C file, and then call on it from your swift file. Check out this question on how to do that
How to call Objective-C code from Swift