如何在 iPhone 的 Swift iOS 中使用 FBSDK 获取用户电子邮件地址?

Posted

技术标签:

【中文标题】如何在 iPhone 的 Swift iOS 中使用 FBSDK 获取用户电子邮件地址?【英文标题】:How to get user email address using FBSDK in swift iOS for iPhone? 【发布时间】:2017-02-13 06:07:09 【问题描述】:

我是一名自学新手,使用 swift 开发 iPhone 应用程序。我正在使用 FBSDK 设计用于 Facebook 身份验证的登录页面。我已经成功实现了登录和注销的登录按钮。它返回用户名和 ID,但无法绘制用户电子邮件 ID 并显示代码 2500 错误。我也无法使用新用户登录。它会自动使用同一用户登录。

这是错误:

UserInfo=com.facebook.sdk:FBSDKGraphRequestErrorCategoryKey=0, com.facebook.sdk:FBSDKGraphRequestErrorHTTPStatusCodeKey=400, com.facebook.sdk:FBSDKErrorDeveloperMessageKey=An active access token must be used to query information about the current user., com.facebook.sdk:FBSDKGraphRequestErrorGraphErrorCode=2500, com.facebook.sdk:FBSDKGraphRequestErrorParsedJSONResponseKey=
    body =     
        error =         
            code = 2500;
            "fbtrace_id" = BimF4Nuqx0v;
            message = "An active access token must be used to query information about the current user.";
            type = OAuthException;
        ;
    ;
    code = 400;
)
Successfully logged in with Facebook... 
123
result Optional(
    id = 120008981838163;
    name = "Nisha ios";
)
Did Logout of Facebook

这是我在 AppDelegate.swift 中的代码:

import UIKit
import CoreData
import FBSDKCoreKit


@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,  

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool 
        // Override point for customization after application launch.

        FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)

        return true
    


    func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any]) -> Bool 

        var handled=FBSDKApplicationDelegate.sharedInstance().application(app, open: url,
                                                                            sourceApplication: options[UIApplicationOpenURLOptionsKey.sourceApplication] as! String!, annotation: options[UIApplicationOpenURLOptionsKey.annotation])

return handled


    func applicationWillResignActive(_ application: UIApplication) 
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
         FBSDKAppEvents.activateApp()
    

这是我在 ViewController.swift 中的代码:

import UIKit
import FBSDKLoginKit
import FBSDKCoreKit


class ViewController: UIViewController, UITextFieldDelegate, FBSDKLoginButtonDelegate,  


    @IBOutlet var emailField: UITextField!

    @IBOutlet var passField: UITextField!

    @IBOutlet var customButton: FBSDKLoginButton!


    @IBOutlet var myView: UIView!

    override func viewDidLoad() 
        super.viewDidLoad()

        self.emailField.delegate = self;
        self.passField.delegate = self;

      customButton.readPermissions=["email","public_profile"]
        customButton.delegate=self

        customButton.addTarget(self, action: #selector(handleCustomFBLogin), for: UIControlEvents.touchUpInside)

 func handleCustomFBLogin()

   //  FBSDKLoginManager().logIn(withReadPermissions: ["email","public_profile"], from: self)
    //    (result, error) -> Void in
    //  if error != nil 
       //   print("custom FB Login Failed",error)
       //       
    //
                self.showEmail()
                print(123)
      


    func showEmail()
    
        FBSDKGraphRequest(graphpath: "/me", parameters: ["fields": "email, id, name"]).start 
            (connection, result, err) in
          if(err == nil)
           
                print("result \(result)")
            
           else
            
                print("error \(err)")
            
        

    

    public func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) 

        if error != nil
        
            print(error)
            return

        
        else
            print("Successfully logged in with Facebook... ")

        
        //showEmail()
    

    func loginButtonDidLogOut(_ loginButton: FBSDKLoginButton!)

        print("Did Logout of Facebook")

    

在 func handleCustomFBLogin() 中,我注释了一些代码。如果我取消注释它们,我将无法获得用户名或 ID,只会收到代码 2500 错误。

谁能告诉我我做错了什么?还帮助我使用新用户登录而不是自动使用同一用户登录? 提前非常感谢:-)

【问题讨论】:

***.com/questions/9347104/… 【参考方案1】:

我正在使用它,它对我来说工作正常。请确保您用于登录的帐户已公开电子邮件和其他详细信息。您只能获取 Facebook 用户的公开详细信息。其次,你的令牌应该是有效的。

   func getFBUserData()
    

            showIndicator()

            if((FBSDKAccessToken.currentAccessToken()) != nil

            

                FBSDKGraphRequest(graphPath: "me",

                                    parameters: ["fields": "id, name, first_name, last_name, picture.type(large), email , gender"]).startWithCompletionHandler(

                                     (connection, result, error) -> Void in

                                        self.hideIndicator()

                    if (error == nil)

                    

                        self.objSocialInfo = SignupUserStructure()

                        self.objSocialInfo.Name = String(result.objectForKey("first_name")!) + " " +  String(result.objectForKey("last_name")!)

                        self.objSocialInfo.Email = String(result.objectForKey("email")!)

                        self.objSocialInfo.ProfilePicUrl = (result.objectForKey("picture")?.objectForKey("data")?.objectForKey("url") as? String)!

                        self.objSocialInfo.SocialId = String(result.objectForKey("id")!)

                        self.objSocialInfo.Gender = String(result.objectForKey("gender")!)

                    )
            
    

【讨论】:

非常感谢。我的电子邮件没有经过验证。这就是它不会返回用户电子邮件的原因。当我添加 FBSDKAccessToken 条件时,错误被清除。再次感谢。 欢迎@Nisha 快乐的帮助。你可以接受我的回答。 :-) 我做到了。谢谢

以上是关于如何在 iPhone 的 Swift iOS 中使用 FBSDK 获取用户电子邮件地址?的主要内容,如果未能解决你的问题,请参考以下文章

iOS - 如何在应用程序中使 iPhone 静音/响铃

如何在 Swift iOS 中使 web 视图不可点击

在 swift 中使 URL 链接属性和可点击以及可编辑的 Textview

如何在 Xcode 中使元素具有百分比宽度

如何在 iPhone 6 中使 iFrame 响应?

在pickerview(Swift 3,Xcode)中使(第一)行不可选择