Swift - 从Facebook登录获取错误

时间:2018-05-28 03:39:30

标签: ios facebook firebase firebase-authentication swift4

刚开始我已经看了很多例子,但似乎无法找到解决方案。好吧,我以为我做了,但似乎没有用。

我要做的是使用适用于Facebook的Firebase身份验证登录方法,顺便说一句。我的问题是,当facebook方法抛出电子邮件/凭证已存在的错误时,我想链接密码身份验证凭据和facebook身份验证凭据。我看了here我可以使用error.email,但它没有让我选择访问email.error。我可能会遗漏一些东西,而且我花了很多时间试图解决这个问题。

这是我的代码:

func signInFacebookUser() {
    let fbLoginManager = FBSDKLoginManager()
    fbLoginManager.logIn(withReadPermissions: ["public_profile", "email"], from: self) { (result, error) in
        if let error = error {
            self.errorMessagePopUp(title: "Failed to login", message: error)
            return
        }

        guard let accessToken = FBSDKAccessToken.current() else {
        print("Failed to get access token")
        return
   }

   let credential = FacebookAuthProvider.credential(withAccessToken: accessToken.tokenString)

   Auth.auth().signIn(with: credential, completion: { (user, error) in
        if let error = error {

        let errCode = AuthErrorCode(rawValue: error._code)!

        switch errCode {

              case .accountExistsWithDifferentCredential:
              // somehow obtain email right here.
              self.showSigninForm(attributes: self.attributes(), style: .light)
              return

             default:
             return
          }
       }

       self.performSegue(withIdentifier: "signInBtnPressed", sender: nil)
    })
  }
}

2 个答案:

答案 0 :(得分:1)

这适用于我的Swift4

@objc func loginButtonClicked() {
    var alertController = UIAlertController()
    let loginManager = LoginManager()
    loginManager.logIn(readPermissions: [ReadPermission.email], >viewController: self, completion: {loginResult in
                    switch loginResult {
                    case .failed(let error):
                        print(error)
                    case .cancelled:
                        print("User cancelled login.")
                    case .success(_, _, let accessToken):
                        print(accessToken)

                    }

    })
}
 func getDataUser() {
        let request = GraphRequest(graphPath: "me?fields=first_name,last_name,email",
                                   parameters:[:],
                                   httpMethod: .GET)
        request.start { httpResponse, result in
            switch result {
            case .success(let response): do {
                print("Graph Request Succeeded: \(response)")
                let dicval = response.dictionaryValue
                let email = dicval?.keys
                print("Graph Request Succeeded: \(String(describing: email))")
                }
            case .failed(let error):
                print("Graph Request Failed: \(error)")
            }

        }
    }
}

答案 1 :(得分:0)

试用此代码

@IBAction func facebookLoginButtonTapped(_ sender: UIButton) {
        if Utility.checkInternet(){
            let fbLoginManager: FBSDKLoginManager = FBSDKLoginManager()
            fbLoginManager.logIn(withReadPermissions: ["email", "public_profile"], from: self) { (result, error) in
                if (error == nil){
                    let fbLoginResult: FBSDKLoginManagerLoginResult = result!
                    if fbLoginResult.grantedPermissions != nil {
                        if(fbLoginResult.grantedPermissions.contains("email")){
                            self.facebookLogin()
                        }
                    }
                }
            }
        }
        else{
            Utility.showAlert("Connection Error!", message: "Please check internet connection and retry.", viewController: (self.window?.rootViewController)!)
        }
    }
func facebookLogin() {
        Utility.showProgress("")
        if((FBSDKAccessToken.current()) != nil) {

            FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"id, name, first_name, last_name, picture.type(large), email "]).start(completionHandler: { (connection, result, error) in
                if result == nil {
                }
                else{
                    self.userResults = result as! [String : AnyObject]
                    self.email = (self.userResults["email"] as? String) ?? ""
                    if (self.email != "") {

                    }
                    else{
                        Utility.showAlert("Login Faild", message: error?.localizedDescription, viewController: self)
                    }
                }
            })
        }
    }