Home > OS >  How to run code immediately after facebook login?
How to run code immediately after facebook login?

Time:08-05

I am making an app supporting login with email and password, login with google and login with facebook. I have implemented login with email and google and am using firebase for user authentication and storage. For login with google, I am able to dismiss the current screen after login is successful, and using delegates am able to pass information back that the login was successful, and the login button changes to log out on the main screen. However, there seems to have been some kind of update in the facebook SDK and tutorials which I have been able to find do not seem to answer my question: How can I dismiss my screen after login is complete? All I had to do to hook facebook login was register my app on their website, then add the following to my facebook/google login view controller viewDidLoad() method:

    let loginButton = FBLoginButton()
    loginButton.center = view.center
            view.addSubview(loginButton)
    self.view.addSubview(loginButton)

After adding this, there is a fully functioning button in my app:

enter image description here

This also updates to "Log Out" when login is complete. My question is, is there some methods where I can customize the login, so that when it is complete I can call self.dismiss().

By the way, I found a "LoginButtonDelegate" I can add to the view controller which will require the following functions to be added:

func loginButton(_ loginButton: FBLoginButton, didCompleteWith result: LoginManagerLoginResult?, error: Error?) {
    
}

func loginButtonDidLogOut(_ loginButton: FBLoginButton) {

}

Do I have to use these methods? I tried to use the first one to print something when login is done but nothing happened. Thanks in advance for your time

CodePudding user response:

Your ViewController have to conform to LoginButtonDelegate protocol, and you need to set the delegate of your loginButton in order to get your LoginButtonDelegate methods called.

loginButton.delegate = self


But I would suggest to do the job manually using the LoginManager so you have more flexibility here:

  1. Create a custom button:
let fbLoginButton = UIButton()
// Customize it
// ...
fbLoginButton.addTarget(self, action: #selector(onButtonTap), for: .touchUpInside)
view.addSubview(fbLoginButton)
  1. Call the login method of the LoginManager class on button tap:
@objc func onButtonTap() {
        LoginManager().logIn(permissions: [.email, .publicProfile]) {
            switch $0 {
            case let .success(grantedPermissions, declinedPermissions, token):
                // success
                // ...
            case let .failed(error):
                // fail
                // ...
            case .cancelled:
                // cancel
                // ...
            }
        }
    }
  • Related