1

I am struggling with the issue of Facebook login, Yesterday Facebook login working correctly but today when I run my app it's not working don't know why, why it's not working suddenly I already configured all things related to Facebook login in Facebook develop console everything is configured Please help me out if you have any idea, I already enable Keychain sharing also.enter image description here

Code for Facebook Login

@IBAction func onClickFacebookLoginAction(_ sender: Any) {

    var message = String()
    if Reachability.isConnectedToNetwork() == true{

        let loginView:FBSDKLoginManager = FBSDKLoginManager()
        loginView.loginBehavior = FBSDKLoginBehavior.web
        loginView.logIn(withReadPermissions: ["email","public_profile","user_friends"], from: self, handler: { (result, error) in
            if(error != nil){

                print("Error while try to login with facebook-\(error?.localizedDescription)")
            }else if (result?.isCancelled)!{

                print("User cancel the facebook login")
            }else{

                if result?.grantedPermissions != nil{
                    if (result?.grantedPermissions .contains("email"))!{
                        self.ShowProgressHUD()
                        self.fetchUserInfo()
                    }else{
                        message = message.appending("Facebook email permission error")
                        self.showAlertMessage(message: message, title: "")
                    }
                }
            }
        })
    }
}

func fetchUserInfo() -> Void {

    if (FBSDKAccessToken.current() != nil) {

        let graphRequest:FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "/me", parameters:["fields": "id, first_name, last_name, name, email, picture"])
        graphRequest.start(completionHandler: { (connection, result, error) in

            if(error != nil){

                self.showAlertMessage(message: (error?.localizedDescription)!, title: "")

            }
            else
            {
                 print("Result is:\(result)")
                self.dictionary = result as! [String : AnyObject]
                let name = self.dictionary["name"] as!String
                let email = self.dictionary["email"] as! String
                let token = FBSDKAccessToken.current().tokenString

                print("name is -\(name)")
                print("email is -\(email)")
                print("token is -\(token)")


                DispatchQueue.main.async {

                    let SelectionViewObj = self.storyboard?.instantiateViewController(withIdentifier: "ViewController") as! ViewController
                    self.navigationController?.pushViewController(SelectionViewObj, animated: true)
                }
            }
        })
    }
}
Sanjeet Verma
  • 551
  • 4
  • 15

2 Answers2

1

This is the code i am using to authenticate facebook.its working like a charm.Just check or replace with this.

self.fbLoginManager = FBSDKLoginManager.init()
fbLoginManager.loginBehavior = FBSDKLoginBehavior.web
self.fbLoginManager.logIn(withReadPermissions: ["email"], from: self) { (result, error) -> Void in
    if (error == nil) {
        let fbloginresult : FBSDKLoginManagerLoginResult = result!
        if fbloginresult.grantedPermissions != nil && fbloginresult.grantedPermissions.contains("email") {
            if((FBSDKAccessToken.current()) != nil){
                FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"id, first_name, last_name, email, gender, birthday, location"]).start(completionHandler: { (connection, result, error) -> Void in
                    if error != nil {
                        print(error?.localizedDescription ?? "error in facebook login...!")
                        return
                    }
                    if let dict = result as? NSDictionary {
                        print("facebook login result --->\n\(dict)")
                        guard let id = dict["id"] else {
                            print("Ooops... id = nil")
                            return
                        }
                        //  let firstName: String = dict["first_name"] as? String ?? ""
                       // let lastName : String = dict["last_name"] as? String ?? ""
                      //  let email : String = dict["email"] as? String ?? ""

                        self.fbLoginManager.logOut()
                    }
                })
            }
        } else {
            print("facebook ---> login canceled")
        }
    } else {
        print(error?.localizedDescription ?? "facebook login has error")
    }
}
Dharma
  • 3,007
  • 3
  • 23
  • 38
  • i think remove that project from fb developer console & Create new project and try this .... – Dharma Jun 08 '17 at 12:06
  • My application is live on App Store and now I am adding some features If I removed then may be Facebook login working stoped in live also – Sanjeet Verma Jun 08 '17 at 12:08
0

This is how I used to log in with Facebook,

@IBAction func act_loginFB(_ sender: UIButton) {
    let fbLoginManager : FBSDKLoginManager = FBSDKLoginManager()
    fbLoginManager.logIn(withReadPermissions: ["public_profile", "email",], from: self) { (result, error) -> Void in
        if (error == nil){
            let fbloginresult : FBSDKLoginManagerLoginResult = result!
            if(fbloginresult.grantedPermissions.contains("email"))
            {
                self.getFBUserData()
            }
        }
    }
}

func getFBUserData(){
    if((FBSDKAccessToken.current()) != nil){
        FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, picture.type(large), email"]).start(completionHandler: { (connection, result, error) -> Void in
            if (error == nil){
                //everything works print the user data
                print(result)
                let data: [String:AnyObject] = (result as? [String : AnyObject])!
                print(data)
                let email: String = data["email"]! as! String
                print(email)
            }
        })
    }
}

Check you added the correct FacebookAppID and FacebookDisplayName in the info.plist

Praveen Kumar
  • 298
  • 2
  • 15
  • I want to open Login behaviour as a web don't want to open in safari browser,In browser it's working correctly in my code also – Sanjeet Verma Jun 08 '17 at 11:41
  • @Sanjeetverma add this `fbLoginManager.loginBehavior = FBSDKLoginBehavior.web` after this line `let fbLoginManager : FBSDKLoginManager = FBSDKLoginManager()` – Praveen Kumar Jun 08 '17 at 11:44
  • I used in my code also if you want then you can check my code above in my Question also Ok let me try your answer first – Sanjeet Verma Jun 08 '17 at 11:45
  • same result can you once you try with your code with login behaviour it's working If I use safari browser – Sanjeet Verma Jun 08 '17 at 11:50
  • @Sanjeetverma I think there is no wrong in your code, the problem is somewhere, verify that you followed every step from the tutorial you followed else try some other. The generic code to facebook login is the one I mentioned above. Presenting the login via web browser or native is up to you which can be attained from `FBSDKLoginBehavior ` – Praveen Kumar Jun 08 '17 at 11:51
  • @pravin I followed Facebook developer docs and did step by step I am also not getting where exactly lacking the issue or error from Facebook sdk side I did lot of time Facebook login never get this kind of error first time I got this kind of error – Sanjeet Verma Jun 08 '17 at 11:54
  • when I run the application I am getting error in console like this canOpenURL: failed for URL: "fbauth2:/" - error: "The operation couldn’t be completed. (OSStatus error -10814.)" – Sanjeet Verma Jun 08 '17 at 11:59
  • check whether you added URL Schemes in info.plist – Dharma Jun 08 '17 at 12:08
  • @Sanjeetverma In your facebook developer account's app settings add the correct bundle Id – Praveen Kumar Jun 08 '17 at 12:09