从Objective-C到Swift的FBSDKLoginManager代码

任何人请帮助我如何将FBSDKLoginManager代码转换为swift编程在此先感谢在这里我将代码附加在Objective-C

- (IBAction)btnFacebookPressed:(id)sender { FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init]; login.loginBehavior = FBSDKLoginBehaviorBrowser; [login logInWithReadPermissions:@[@"email"] handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) { if (error) { // Process error } else if (result.isCancelled) { // Handle cancellations } else { if ([result.grantedPermissions containsObject:@"email"]) { NSLog(@"result is:%@",result); [self fetchUserInfo]; [login logOut]; // Only If you don't want to save the session for current app } } }]; } 

我的看法控制器代码是:

 class ViewController: UIViewController, FBSDKLoginButtonDelegate { let facebookReadPermissions = ["public_profile", "email", "user_friends"] override func viewDidLoad() { super.viewDidLoad() self.performSegueWithIdentifier("showView", sender: self) /*for view in self.fbLoginView.subviews as! [UIView] { if view.isKindOfClass(UIButton) { let customButton = view as! UIButton //customButton.removeFromSuperview() customButton.setTitle("LOGIN WITH FACEBOOK", forState: .Normal) customButton.backgroundColor = UIColor(red: 72/255.0, green: 128/255.0, blue: 255/255.0, alpha: 1.0) customButton.showsTouchWhenHighlighted = true customButton.frame = CGRectMake(90, 15, 210, 16) customButton.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Center //customButton.willMoveToSuperview(fbLoginView) } if (view.isKindOfClass(UILabel)) { var loginLabel = view as! UILabel; loginLabel.text = "LOGIN WITH FACEBOOK" //loginLabel.textColor = UIColor.blackColor() //loginLabel.textAlignment = NSTextAlignment(rawValue : 50) //loginLabel.frame = CGRectMake(50, 50, 265, 45) loginLabel.removeFromSuperview() } }*/ } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if (segue.identifier == "showView") { var vc: ViewController1 = segue.destinationViewController as! ViewController1 } } // Facebook Delegate Methods func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!) { println("User Logged In") if ((error) != nil) { // Process error println(error.localizedDescription) } else if result.isCancelled { // Handle cancellations } else { // If you ask for multiple permissions at once, you // should check if specific permissions missing println("Login complete.") /*if result.grantedPermissions.contains("email") { // Do work //self.performSegueWithIdentifier("showView", sender: self) }*/ } } func loginButtonDidLogOut(loginButton: FBSDKLoginButton!) { println("User Logged Out") } /*func returnUserData() { let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: nil) graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in if ((error) != nil) { // Process error println("Error: \(error)") } else { println("fetched user: \(result)") let userName : NSString = result.valueForKey("name") as! NSString println("User Name is: \(userName)") let userEmail : NSString = result.valueForKey("email") as! NSString println("User Email is: \(userEmail)") } }) } 

* /

 override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func customButton(sender: AnyObject) { var fbLoginManager : FBSDKLoginManager = FBSDKLoginManager() fbLoginManager.loginBehavior = FBSDKLoginBehavior.Browser fbLoginManager.logInWithReadPermissions(self.facebookReadPermissions, handler: { (result, error) -> Void in if (error == nil){ var fbloginresult : FBSDKLoginManagerLoginResult = result if(fbloginresult.grantedPermissions.contains("email")) { self.fetchUserInfo() fbLoginManager.logOut() } } }) } func fetchUserInfo(){ 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){ println(result) result.valueForKey("email") as! String result.valueForKey("id") as! String result.valueForKey("name") as! String result.valueForKey("first_name") as! String result.valueForKey("last_name") as! String } }) } } } 

当我运行我的应用程序。 自定义button根本不工作事件不发生

这是你的代码的快速版本

  @IBAction func btnFBLoginPressed(sender: AnyObject) { var fbLoginManager : FBSDKLoginManager = FBSDKLoginManager() //fbLoginManager.loginBehavior = FBSDKLoginBehavior.Browser fbLoginManager.logInWithReadPermissions(["email"], handler: { (result, error) -> Void in if (error == nil){ var fbloginresult : FBSDKLoginManagerLoginResult = result if(fbloginresult.isCancelled) { //Show Cancel alert } else if(fbloginresult.grantedPermissions.contains("email")) { self.returnUserData() //fbLoginManager.logOut() } } }) } 

更新

 func returnUserData(){ 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){ println(result) result.valueForKey("email") as! String result.valueForKey("id") as! String result.valueForKey("name") as! String result.valueForKey("first_name") as! String result.valueForKey("last_name") as! String } }) } } 

作为参考,你可以尝试这个链接点击

 let facebookReadPermissions = ["public_profile", "email", "user_friends"] func loginToFacebookWithSuccess(successBlock: () -> (), andFailure failureBlock: (NSError?) -> ()) { if FBSDKAccessToken.currentAccessToken() != nil { //For debugging, when we want to ensure that facebook login always happens //FBSDKLoginManager().logOut() //Otherwise do: return } FBSDKLoginManager().logInWithReadPermissions(self.facebookReadPermissions, handler: { (result:FBSDKLoginManagerLoginResult!, error:NSError!) -> Void in if error != nil { //According to Facebook: //Errors will rarely occur in the typical login flow because the login dialog //presented by Facebook via single sign on will guide the users to resolve any errors. // Process error FBSDKLoginManager().logOut() failureBlock(error) } else if result.isCancelled { // Handle cancellations FBSDKLoginManager().logOut() failureBlock(nil) } else { // If you ask for multiple permissions at once, you // should check if specific permissions missing var allPermsGranted = true //result.grantedPermissions returns an array of _NSCFString pointers let grantedPermissions = result.grantedPermissions.allObjects.map( {"\($0)"} ) for permission in self.facebookReadPermissions { if !contains(grantedPermissions, permission) { allPermsGranted = false break } } if allPermsGranted { // Do work let fbToken = result.token.tokenString let fbUserID = result.token.userID //Send fbToken and fbUserID to your web API for processing, or just hang on to that locally if needed //self.post("myserver/myendpoint", parameters: ["token": fbToken, "userID": fbUserId]) {(error: NSError?) ->() in // if error != nil { // failureBlock(error) // } else { // successBlock(maybeSomeInfoHere?) // } //} successBlock() } else { //The user did not grant all permissions requested //Discover which permissions are granted //and if you can live without the declined ones failureBlock(nil) } } }) }