Search code examples
swiftfacebook-ios-sdk

FBSDKLoginManagerLoginResult valueForUndefinedKey when trying to get user's email


I'm trying to get user's name , email and id from FBSDKLoginManagerLoginResult and get an error:

Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ valueForUndefinedKey:]: this class is not key value coding-compliant for the key email.'

Here's the code :

   class ViewController: UIViewController, FBSDKLoginButtonDelegate {

        @IBOutlet weak var fbLogin: FBSDKLoginButton!
        override func viewDidLoad() {
            super.viewDidLoad()
       fbLogin.readPermissions = ["public_profile", "email"]
            fbLogin.delegate = self
    }

        func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!) {


            if ((error) != nil)
            {
                NSLog("User Logged In")
            }
            else if result.isCancelled {
                 NSLog("User cancels")
            }
            else {
                if result.grantedPermissions.contains("email")
                {             
                   let userEmail : String = result.valueForKey("email") as! String //here I get crash
                    NSLog("User Email is: \(userEmail)")
                }
            }
        }
    }

Also, I can't find list of available keys


Solution

  • Looks like you need to make a FBSDKGraphRequest. I have

    func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: NSError!) {
    
        if ((error) != nil) {
            // Process error
        } else if result.isCancelled {
            // Handle cancellations
        } else {
            let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields" : "id, email, name"])
            graphRequest.start(completionHandler: { (connection, result, error) -> Void in
                if ((error) != nil) {
                    print("Error: \(error)")
                } else {
                    if let user : NSString = result!.value(forKey: "name") as? NSString {
                        //print("user2: \(user)")
                        self.userLabel.text = "Logged in as \(user)"
                    }
                    if let id : NSString = result!.value(forKey: "id") as? NSString {
                        self.fbId = id
                        //print("id: \(id)")
                    }
                    if let email : NSString = result!.value(forKey: "email") as? NSString {
                        print("email: \(email)")
                    }
                }
            })
        }
    }
    

    This example is using swift ver. 3 (xcode beta 3).