2016-07-29 67 views
1

我試圖讓用戶的姓名,電子郵件地址和ID從FBSDKLoginManagerLoginResult,並得到一個錯誤時:FBSDKLoginManagerLoginResult valueForUndefinedKey試圖獲得用戶的電子郵件

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

下面的代碼:

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

而且,我找不到可用密鑰列表

回答

3

看起來您需要製作FBSDKGraphRequest。我有

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

本例使用swift ver。 3(xcode beta 3)。

+0

好!除了:valueForKey(而不是value(forKey:和graphRequest.startWithCompletionHandler,而不是graphRequest.start)( – user2976267

+0

請原諒,這是swift ver。3.我將這個添加到我的答案中 – kometen

+0

這就是我討厭swift的原因:他們不喜歡不要使廢棄的方法,他們強迫你重寫整個項目:) – user2976267

相關問題