Mahalakshmi.J Mahalakshmi.J - 6 months ago 120
Swift Question

FBSDKLoginManager code from Objective-C to swift

Any one please help me how to convert the FBSDKLoginManager code into swift programming Thanks in advance here i attached the code in 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
}
}
}];
}


My view Controller Code Is:

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


While i'm running my app. The custom button is not at all working the event is not occurring

Answer

This is swift version of your code

 @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()
        }
    }
  })
}

Update

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