自定义Facebook登录按钮iOS

时间:2016-02-02 17:44:35

标签: ios objective-c facebook

我刚刚将Facebook iOS SDK与我的应用程序集成,登录效果很好。也就是说,SDK似乎没有给我自定义登录按钮的选项(它为我提供了屏幕中间那个丑陋的默认按钮)。我在我的应用程序中使用Storyboard - 如何将我自己的按钮连接到他们提供的代码?我已经看到一些较旧的答案发布到Stack,但FB文档后来发生了变化:/

Viewcontroller.m

 FBSDKLoginButton *loginButton = [[FBSDKLoginButton alloc] init];
 loginButton.center = self.view.center;
 [self.view addSubview:loginButton];

8 个答案:

答案 0 :(得分:35)

在故事板中创建自己的自定义按钮。将操作挂钩到myButtonPressed

- (void)viewDidLoad {
    [super viewDidLoad];
    self.loginButton = [[FBSDKLoginButton alloc] init];
    self.loginButton.hidden = YES;
}

- (void)myButtonPressed {
    [self.loginButton sendActionsForControlEvents: UIControlEventTouchUpInside];
}

答案 1 :(得分:16)

针对Swift 3进行了更新

@IBAction func fblogin(_ sender: Any) {
    let loginManager = LoginManager()
    UIApplication.shared.statusBarStyle = .default  // remove this line if not required 
    loginManager.logIn([ .publicProfile,.email ], viewController: self) { loginResult in
        print(loginResult)

        //use picture.type(large) for large size profile picture
        let request = GraphRequest(graphPath: "me", parameters: ["fields":"email,name,gender,picture"], accessToken: AccessToken.current, httpMethod: .GET, apiVersion: FacebookCore.GraphAPIVersion.defaultVersion)
        request.start { (response, result) in
            switch result {
            case .success(let value):
                print(value.dictionaryValue)
            case .failed(let error):
                print(error)
            }
        }
    }
}

对于Objective-C

您可以在UIButton点击事件

上调用此方法
-(void)fblogin{

   FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
    if ([UIApplication.sharedApplication canOpenURL:[NSURL URLWithString:@"fb://"]])
    {
        login.loginBehavior = FBSDKLoginBehaviorSystemAccount;
    }

    [login logInWithReadPermissions:@[@"public_profile", @"email"] handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
        if (error)
        {
            NSLog(@"Unexpected login error: %@", error);
            NSString *alertMessage = error.userInfo[FBSDKErrorLocalizedDescriptionKey] ?: @"There was a problem logging in. Please try again later.";
            NSString *alertTitle = error.userInfo[FBSDKErrorLocalizedTitleKey] ?: @"Oops";
            [[[UIAlertView alloc] initWithTitle:alertTitle
                                        message:alertMessage
                                       delegate:nil
                              cancelButtonTitle:@"OK"
                              otherButtonTitles:nil] show];
        }
        else
        {
            if(result.token)   // This means if There is current access token.
            {

                [[[FBSDKGraphRequest alloc] initWithGraphPath:@"me"
                                                   parameters:@{@"fields": @"picture, name, email"}]
                 startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id userinfo, NSError *error) {
                     if (!error) {


                         dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
                         dispatch_async(queue, ^(void) {

                            dispatch_async(dispatch_get_main_queue(), ^{

                                // you are authorised and can access user data from user info object 

                             });
                         });

                     }
                     else{

                         NSLog(@"%@", [error localizedDescription]);
                     }
                 }];
            }
            NSLog(@"Login Cancel");
        }
    }];
}

答案 2 :(得分:3)

有关自定义按钮的文档的新URL:

https://developers.facebook.com/docs/facebook-login/ios/advanced

或者,如果你只是想知道在点击auth按钮时要做什么,请在"按下按钮"方法(不要忘记将该方法与您的按钮相关联):

#import <FBSDKLoginKit/FBSDKLoginKit.h>
#import <FBSDKCoreKit/FBSDKCoreKit.h>

然后

- (IBAction)facebookAuthButtonTapped:(id)sender {

    FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
    [login
     logInWithReadPermissions: @[@"public_profile"]
     fromViewController:self
     handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
         if (error) {
             NSLog(@"Process error");
         } else if (result.isCancelled) {
             NSLog(@"Cancelled");
         } else {
             NSLog(@"Logged in");
         }
     }];
}

答案 3 :(得分:1)

SwiftUI解决方案

import SwiftUI
import FBSDKLoginKit
import Firebase

struct FaceBookLoginButton: UIViewRepresentable {
    
    func makeCoordinator() -> FBSignInCoordinator {
        return FBSignInCoordinator()
    }
    
    func makeUIView(context: UIViewRepresentableContext<FaceBookLoginButton>) -> FBLoginButton {
        let view = FBLoginButton()
        view.permissions = ["email"]
        view.delegate = context.coordinator
        
        // normal
        view.setTitleColor(.clear, for: .normal)
        view.setImage(nil, for: .normal)
        view.setBackgroundImage(nil, for: .normal)
        
        // tapped
        view.setTitleColor(.clear, for: .highlighted)
        view.setImage(nil, for: .highlighted)
        view.setBackgroundImage(nil, for: .highlighted)
        return view
    }
    
    func updateUIView(_ uiView: FBLoginButton, context: UIViewRepresentableContext<FaceBookLoginButton>) {}
    
}

答案 4 :(得分:0)

来自Facebook文档:(https://developers.facebook.com/docs/swift/login

import FacebookCore
import FacebookLogin

func viewDidLoad() {    
  // Add a custom login button to your app
  let myLoginButton = UIButton(type: .Custom)]
  myLoginButton.backgroundColor = UIColor.darkGrayColor()
  myLoginButton.frame = CGRect(0, 0, 180, 40);
  myLoginButton.center = view.center;
  myLoginTitle.setTitle("My Login Button" forState: .Normal)

  // Handle clicks on the button
  myLoginButton.addTarget(self, action: @selector(self.loginButtonClicked) forControlEvents: .TouchUpInside) 

  // Add the button to the view
  view.addSubview(myLoginButton)
}

// Once the button is clicked, show the login dialog
@objc func loginButtonClicked() {
  let loginManager = LoginManager()
  loginManager.logIn([ .PublicProfile ], viewController: self) { loginResult in
    switch loginResult {
    case .Failed(let error): 
      print(error)
    case .Cancelled:
      print("User cancelled login.")
    case .Success(let grantedPermissions, let declinedPermissions, let accessToken):
      print("Logged in!")
  }
}

答案 5 :(得分:0)

Swift 4.0 将操作设置为您的按钮。

func loginButtonClicked() {
        let loginManager = LoginManager()
        loginManager.logIn(readPermissions: [.publicProfile], viewController: self) { (loginResult) in
            switch loginResult {
            case .failed(let error):
                print(error)
            case .cancelled:
                print("User cancelled login.")
            case .success(let grantedPermissions, let declinedPermissions, let accessToken):
                print("Logged in! \(grantedPermissions) \(declinedPermissions) \(accessToken)")
                self.getFBUserData()
            }
        }
    }

答案 6 :(得分:0)

它对我迅速有效

import FacebookLogin
import FBSDKCoreKit

func connectFacebook() {
        let loginManager = LoginManager()
        loginManager.logIn(permissions: ["user_hometown"],
                           from: nil) { (result, error) in
                            if let result = result {
                                print("Token: \(result.token?.tokenString ?? "")")
                            }
        }
    }

答案 7 :(得分:0)

Swift 5.0 为按钮设置操作

    let loginManager = LoginManager()
    loginManager.logIn(permissions: [.publicProfile], viewController: self) { (loginResult) in
             switch loginResult {
             case .failed(let error):
                 print(error)
             case .cancelled:
                 print("User cancelled login.")
             case .success(let grantedPermissions, let declinedPermissions, let accessToken):
                 print("Logged in! \(grantedPermissions) \(declinedPermissions) \(accessToken)")
                // self.getFBUserData()
             }
         }