Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FBSDKLoginManager code from Objective-C to swift

Tags:

ios

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

like image 391
Mahalakshmi.J Avatar asked Aug 17 '15 11:08

Mahalakshmi.J


2 Answers

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
           }
        })
     }
  }
like image 172
EI Captain v2.0 Avatar answered Nov 19 '22 19:11

EI Captain v2.0


for reference you can try this link click

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)
        }
    }
})
}
like image 3
amit gupta Avatar answered Nov 19 '22 21:11

amit gupta