ios 自定义 Facebook 登录按钮 - 集成后

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36380389/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 08:51:04  来源:igfitidea点击:

Customized Facebook Login Button - After integration

iosswiftfacebook

提问by Jordan Benge

I am trying to customize the Facebook login button after following this guide. Everything is integrated correctly, I can login to Facebook, and logout without a hitch.

遵循本指南后,我尝试自定义 Facebook 登录按钮。一切都已正确集成,我可以登录 Facebook,然后顺利注销。

Now my next goal is to make the screen look like my mock up, this includes placing the login button correctly on the storyboard, but the only issue is that it doesn't show up on the story board, it just appears when I run the simulation. I looked at other overflow answers, but they weren't really helpful as they were geared towards earlier versions of swift / Xcode, and didn't work from what the comments said. My code is exactly the same as the guide, as this is the first screen that I am trying to implement.

现在我的下一个目标是让屏幕看起来像我的模型,这包括将登录按钮正确放置在情节提要上,但唯一的问题是它没有出现在情节提要上,它只在我运行时出现模拟。我查看了其他溢出答案,但它们并没有真正有帮助,因为它们适用于早期版本的 swift / Xcode,并且根据评论所说的内容不起作用。我的代码与指南完全相同,因为这是我尝试实现的第一个屏幕。

Help would be much appreciated.

帮助将不胜感激。

回答by HardikDG

If you want to use the custom facebook SDK buttonyou can create any custom button in the storyboard and provide action in the viewcontroller like this

如果您想使用自定义 facebook SDK 按钮,您可以在故事板中创建任何自定义按钮并在视图控制器中提供这样的操作

Import at top

在顶部导入

import FBSDKCoreKit
import FBSDKLoginKit

Swift 3:

斯威夫特 3:

  @IBAction func loginFacebookAction(sender: AnyObject) {//action of the custom button in the storyboard
    let fbLoginManager : FBSDKLoginManager = FBSDKLoginManager()
    fbLoginManager.logIn(withReadPermissions: ["email"], from: self) { (result, error) -> Void in
      if (error == nil){
        let fbloginresult : FBSDKLoginManagerLoginResult = result!
        // if user cancel the login 
        if (result?.isCancelled)!{
                return
        }
        if(fbloginresult.grantedPermissions.contains("email"))
        {
          self.getFBUserData()
        }
      }
    }
  }

  func getFBUserData(){
    if((FBSDKAccessToken.current()) != nil){
      FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, picture.type(large), email"]).start(completionHandler: { (connection, result, error) -> Void in
        if (error == nil){
          //everything works print the user data
          print(result)
        }
      })
    }
  }

Older Swift version:

较旧的 Swift 版本:

 @IBAction func loginFacebookAction(sender: AnyObject) {//action of the custom button in the storyboard
        let fbLoginManager : FBSDKLoginManager = FBSDKLoginManager()
        fbLoginManager.logInWithReadPermissions(["email"], fromViewController: self) { (result, error) -> Void in
            if (error == nil){
                let fbloginresult : FBSDKLoginManagerLoginResult = result
                if(fbloginresult.grantedPermissions.contains("email"))
                {
                    self.getFBUserData()
                }
            }
        }
    }

    func getFBUserData(){
        if((FBSDKAccessToken.currentAccessToken()) != nil){
            FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, picture.type(large), email"]).startWithCompletionHandler({ (connection, result, error) -> Void in
                if (error == nil){
                    //everything works print the user data
                    print(result)
                }
            })
        }
    }



If you want default facebook loginbutton you can take UIView and set Class* field of the Custom Class** section in the Identity Inspector, we must set the FBLoginValue



如果您想要默认的 facebook 登录按钮,您可以使用 UIView 并设置身份检查器中自定义类**部分的类*字段,我们必须设置FBLoginValue

Ref: Default SDK login button tutorial:http://www.appcoda.com/ios-programming-facebook-login-sdk/

参考:默认 SDK 登录按钮教程:http: //www.appcoda.com/ios-programming-facebook-login-sdk/

Ref: Custom SDK login button for parameters and more info:https://developers.facebook.com/docs/facebook-login/ios

参考:用于参数和更多信息的自定义 SDK 登录按钮:https: //developers.facebook.com/docs/facebook-login/ios

回答by Yakup Ad

POD INSTALL

吊舱安装

source 'https://github.com/CocoaPods/Specs.git'
use_frameworks!
target “ProjectName” do
  pod 'FacebookCore'
  pod 'FacebookLogin'
  pod 'FacebookShare'
end

AppDelegate.swift

AppDelegate.swift

import FacebookLogin
import FBSDKLoginKit
import FacebookCore

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
    return true
}

func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
    return FBSDKApplicationDelegate.sharedInstance().application(application, open: url, sourceApplication: sourceApplication, annotation: annotation)
}

ViewController.swift

视图控制器.swift

import UIKit
import FacebookLogin
import FBSDKLoginKit
import FacebookCore

class ViewController: UIViewController {

override func viewDidLoad() {
    if(FBSDKAccessToken.current() == nil){
        print("Not logged in ")
    }else{
        print("Logged in already")
        getFacebookUserInfo()
    }
}

@IBAction func CustomButton_Click(_ sender: Any) {
    getFacebookUserInfo()
}

func getFacebookUserInfo(){
    let loginManager = LoginManager()
    loginManager.logIn([.publicProfile, .email ], viewController: self) { (result) in
        switch result{
        case .cancelled:
            print("Cancel button click")
        case .success:
            let params = ["fields" : "id, name, first_name, last_name, picture.type(large), email "]
            let graphRequest = FBSDKGraphRequest.init(graphPath: "/me", parameters: params)
            let Connection = FBSDKGraphRequestConnection()
            Connection.add(graphRequest) { (Connection, result, error) in
                let info = result as! [String : AnyObject]
                print(info["name"] as! String)
            }
            Connection.start()
        default:
            print("??")
        }
    }
}
}

Info.plist

信息表

Info.plist --> right click ->OpenAs -->Source Code --> add < dict > .. < /dict >

Info.plist --> 右键->OpenAs -->Source Code --> 添加<dict>..</dict>

<key>CFBundleURLTypes</key>
    <array>
        <dict>
            <key>CFBundleURLSchemes</key>
            <array>
                <string>YOUR APP ID</string>
            </array>
        </dict>
    </array>
    <key>FacebookAppID</key>
    <string>YOUR APP ID</string>
    <key>FacebookDisplayName</key>
    <string>YOUR APP NAME</string>

回答by Srinivasan.M

@IBAction func buttonLogin(_ sender: Any) {

@IBAction func buttonLogin(_ sender: Any) {

    let fbLoginManager : FBSDKLoginManager = FBSDKLoginManager()

    fbLoginManager.logIn(withReadPermissions: ["public_profile","email"], from: self) { (result, error) in

        if (error == nil){
            let fbloginresult : FBSDKLoginManagerLoginResult = result!
            if fbloginresult.grantedPermissions != nil {
                if(fbloginresult.grantedPermissions.contains("email")) {
                    if((FBSDKAccessToken.current()) != nil){
                        FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, picture.type(large), email"]).start(completionHandler: { (connection, result, error) -> Void in
                            if (error == nil){
                               let dict: NSDictionary = result as! NSDictionary
                                if let token = FBSDKAccessToken.current().tokenString {
                                    print("tocken: \(token)")

                                    let userDefult = UserDefaults.standard
                                    userDefult.setValue(token, forKey: "access_tocken")
                                    userDefult.synchronize()
                                }
                                if let user : NSString = dict.object(forKey:"name") as! NSString? {
                                    print("user: \(user)")
                                }
                                if let id : NSString = dict.object(forKey:"id") as? NSString {
                                    print("id: \(id)")
                                }
                                if let email : NSString = (result! as AnyObject).value(forKey: "email") as? NSString {
                                    print("email: \(email)")
                                }
                            }
                        })
                    }
                }
            }
        }
    }
 }

回答by Dan Levy

Welcome to StackOverflow, Shika! That tutorial shows you how to add the button that Facebook provides as part of their SDK. The tutorial tells you centers the button in the center of the device's screen. Facebook allows you to create your own button, if you'd like to. In my opinion, I like it better, because you can play with it in the storyboard, unlike the button created programmatically in Swift. You can use the Facebook docs hereand scroll down to "Custom Login Button". Your code will change, but not by much! If you choose to go this route, make sure to delete the code you copied and pasted to add the button located in viewDidLoad. Also, you can delete the FBSDKLoginButtonDelegate you added at the top of the Swift file.

欢迎来到 StackOverflow,Shika!该教程向您展示了如何添加 Facebook 提供的按钮作为其 SDK 的一部分。本教程告诉您将按钮置于设备屏幕的中央。如果您愿意,Facebook 允许您创建自己的按钮。在我看来,我更喜欢它,因为您可以在故事板中使用它,这与在 Swift 中以编程方式创建的按钮不同。您可以在此处使用 Facebook 文档并向下滚动到“自定义登录按钮”。您的代码会发生变化,但不会有太大变化!如果您选择走这条路线,请确保删除您复制粘贴的代码以添加位于 viewDidLoad 中的按钮。此外,您可以删除在 Swift 文件顶部添加的 FBSDKLoginButtonDelegate。