Facebook Login button for Swift

Soporificdreamer picture Soporificdreamer · Apr 20, 2015 · Viewed 26.6k times · Source

In Xcode if I create a UIView and then add the custom class as FBSDKLoginButton, when I click it leads me through the Facebook login and then returns me to the same page as the FBSDKLoginButton but instead of saying login button it says log out now. How would I go about making that when the login button is clicked it lead to a new view?


I downloaded the Facebook SDK through cocoapods and its my first time working with it so I am confused about this. Thanks for the help!

Answer

veducm picture veducm · Apr 20, 2015

One option would be to set your view controller as a delegate of the FBSDKLoginButton and implement the loginButton:didCompleteWithResult:error: method, which is called when the button is used to login.

Swift

class ViewController: UIViewController, FBSDKLoginButtonDelegate {

    @IBOutlet weak var loginButton: FBSDKLoginButton!        

    override func viewDidLoad() {
        super.viewDidLoad()

        self.loginButton.delegate = self
    }
}

Obj-C

// ViewController.h
@interface ViewController : UIViewController <FBSDKLoginButtonDelegate>

@property (weak, nonatomic) IBOutlet FBSDKLoginButton *loginButton;

@end

// ViewController.m
@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.loginButton.delegate = self;
}

Then, in the loginButton:didCompleteWithResult:error: method you can check the result and error, and if everything is fine, navigate to another view.

Swift

func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!) {
        if ((error) != nil) {
            // Process error
        }
        else if result.isCancelled {
            // Handle cancellations
        }
        else {
            // Navigate to other view
        }   
    }

Obj-C

// ViewController.m
@implementation ViewController

- (void)loginButton:(FBSDKLoginButton *)loginButton 
  didCompleteWithResult:(FBSDKLoginManagerLoginResult *)result
                  error:(NSError *)error {
    if (error) {
        // Process error
    }
    else if (result.isCancelled) {
       // Handle cancellations
    }
    else {
        // Navigate to other view
    }
}

You can find more about how to login with FB in their docs.