Get email and name Facebook SDK v4.4.0 Swift

前端 未结 10 2115
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-08 02:22

TL;TR: How do I get the email and name of a user that is logged in on my app using the facebook SDK 4.4

So far I have managed to get login working, now I can get the

相关标签:
10条回答
  • 2020-12-08 02:33
    let request = GraphRequest.init(graphPath: "me", parameters: ["fields":"first_name,last_name,email, picture.type(large)"], accessToken: AccessToken.current, httpMethod: .GET, apiVersion: FacebookCore.GraphAPIVersion.defaultVersion)
    
    request.start({ (response, requestResult) in
          switch requestResult{
              case .success(let response):
                 print(response.dictionaryValue)
              case .failed(let error):
                 print(error.localizedDescription)
          }
    })
    
    0 讨论(0)
  • 2020-12-08 02:37

    Swift 5

    Will retrieve the user email, first name, last name & their id by using the GraphRequest class:

    // Facebook graph request to retrieve the user email & name
    let token = AccessToken.current?.tokenString
    let params = ["fields": "first_name, last_name, email"]
    let graphRequest = GraphRequest(graphPath: "me", parameters: params, tokenString: token, version: nil, httpMethod: .get)
    graphRequest.start { (connection, result, error) in
    
        if let err = error {
            print("Facebook graph request error: \(err)")
        } else {
            print("Facebook graph request successful!")
    
            guard let json = result as? NSDictionary else { return }
            if let email = json["email"] as? String {
                print("\(email)")
            }
            if let firstName = json["first_name"] as? String {
                print("\(firstName)")
            }
            if let lastName = json["last_name"] as? String {
                print("\(lastName)")
            }
            if let id = json["id"] as? String {
                print("\(id)")
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-08 02:38

    In Swift, you can make a Graph request(as shown by @RageCompex) from the login button's didCompleteWithResult callback.

    func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!)
        {
            print(result.token.tokenString) //YOUR FB TOKEN
            let req = FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"email,name"], tokenString: result.token.tokenString, version: nil, HTTPMethod: "GET")
            req.startWithCompletionHandler({ (connection, result, error : NSError!) -> Void in
                if(error == nil)
                {
                    print("result \(result)")
                }
                else
                {
                    print("error \(error)")
                }
            })
    }
    
    0 讨论(0)
  • 2020-12-08 02:40

    For Swift 3 & Facebook SDK 4.16.0:

    func getFBUserInfo() {
        let request = GraphRequest(graphPath: "me", parameters: ["fields":"email,name"], 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)
            }
        }
    }
    

    and will print:

    Optional(["id": 1xxxxxxxxxxxxx, "name": Me, "email": stackoverflow@gmail.com])
    
    0 讨论(0)
  • 2020-12-08 02:42

    I've used fields in android, so I figured to try it in iOS as well, and it works.

    let req = FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"email,name"], tokenString: accessToken.tokenString, version: nil, HTTPMethod: "GET")
       req.startWithCompletionHandler({ (connection, result, error : NSError!) -> Void in
           if(error == nil) {
                print("result \(result)")
           } else {
                print("error \(error)")
           }
       }
    )
    

    result will print:

    result {
       email = "email@example.com";
       id = 123456789;
       name = "Your Name";
    }
    

    Found that these fields are equal to the User endpoint, see this link where you can see all the fields that you can get.

    Update for Swift 4 and above

    let r = FBSDKGraphRequest(graphPath: "me",
                              parameters: ["fields": "email,name"],
                              tokenString: FBSDKAccessToken.current()?.tokenString,
                              version: nil,
                              httpMethod: "GET")
    
    r?.start(completionHandler: { test, result, error in
        if error == nil {
            print(result)
        }
    })
    

    Update for Swift 5 with FBSDKLoginKit 6.5.0

    guard let accessToken = FBSDKLoginKit.AccessToken.current else { return }
    let graphRequest = FBSDKLoginKit.GraphRequest(graphPath: "me",
                                                  parameters: ["fields": "email, name"],
                                                  tokenString: accessToken.tokenString,
                                                  version: nil,
                                                  httpMethod: .get)
    graphRequest.start { (connection, result, error) -> Void in
        if error == nil {
            print("result \(result)")
        }
        else {
            print("error \(error)")
        }
    }
    
    0 讨论(0)
  • 2020-12-08 02:46

    The framework seem to be updated and the way that worked for me is this:

    import FacebookCore
    
    let graphRequest: GraphRequest = GraphRequest(graphPath: "me", parameters: ["fields":"first_name,email, picture.type(large)"], accessToken: accessToken, httpMethod: .GET)
    
    graphRequest.start({ (response, result) in
          switch result {
          case .failed(let error):
               print(error)
          case .success(let result):
               if let data = result as? [String : AnyObject] {
                  print(data)
               }     
          }
    })
    
    0 讨论(0)
提交回复
热议问题