自定义 Facebook 登录按钮 iOS

12

我刚刚将Facebook iOS SDK集成到我的应用程序中,登录功能运行良好。然而,SDK似乎没有提供自定义登录按钮的选项(它为我提供了那个丑陋的默认按钮位于屏幕中央)。我正在使用我的应用程序故事板 - 我该如何将我的自己的按钮与他们提供的代码连接起来?我看到一些早期的答案发布在Stack上,但FB文档已经改变了 :/

Viewcontroller.m

 FBSDKLoginButton *loginButton = [[FBSDKLoginButton alloc] init];
 loginButton.center = self.view.center;
 [self.view addSubview:loginButton];
8个回答

45

在故事板中制作自定义按钮。将操作连接到myButtonPressed

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

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

27
超脏的解决方案 xD :D - Atef
不行:致命错误:在解包可选值时意外发现了nil - MarksCode
这实际上是一个完美的解决方案,因为使用自定义按钮和登录管理器登录存在问题,登录管理器只能使用readPermission或PublishPermission中的一个进行登录,当您需要两个权限时,这是您唯一的解决方案。 - Mina
非常聪明 - Edwin
非常好的答案 :) +1 赞 - Emre Gürses
非常好的回答。你救了我的一天! - badhanganesh

18

已更新至 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");
        }
    }];
}

3

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

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

或者如果您只想知道在认证按钮被点击时该做什么,请在“按钮点击”方法中执行以下操作(不要忘记将该方法与您的按钮链接):

#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");
         }
     }];
}

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>) {}
    
}


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!")
  }
}

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()
            }
        }
    }

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()
             }
         }

0

这对我来说很有效的 Swift

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 ?? "")")
                            }
        }
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接