在ios和swift中使用firebase登录Facebook,但无法获得用户凭据



我正试图将facebook登录集成在我的应用程序中(已经有GOOGLE登录设置),但在didCompleteWithResult函数中,当我调用凭据

let credential =  FIRFacebookAuthProvider.credentialWithAccessToken(FBSDKAccessToken.currentAccessToken().tokenString)

我得到一个错误:fatal error: unexpectedly found nil while unwrapping an Optional value

和每次我按下我的登录按钮,我必须输入我的电子邮件地址和密码,在此之前,我得到另一个错误:2016-07-04 00:34:54.228 PrePathSigningIn[9693:438627] -canOpenURL: failed for URL: "fbauth2:/" - error: "(null)" 2016-07-04 00:34:54.248 PrePathSigningIn[9693:438627] -canOpenURL: failed for URL: "fbauth2:/" - error: "(null)" 在我完成登录后,我的safari页面没有带我回到我的应用程序页面

my appdelegate file:

import UIKit
import CoreData
import Firebase
import IQKeyboardManagerSwift
import GoogleSignIn
import FBSDKCoreKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate , GIDSignInDelegate {
var window: UIWindow?

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.
    FIRApp.configure()
    FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
    IQKeyboardManager.sharedManager().enable = true
    GIDSignIn.sharedInstance().clientID = FIRApp.defaultApp()?.options.clientID
    GIDSignIn.sharedInstance().delegate = self
    return true
}

////////////////////////////////////////
//
//Google signin
//
func application(application: UIApplication,
    openURL url: NSURL, options: [String: AnyObject]) -> Bool {
        GIDSignIn.sharedInstance().handleURL(url,
            sourceApplication: options[UIApplicationOpenURLOptionsSourceApplicationKey] as? String,
            annotation: options[UIApplicationOpenURLOptionsAnnotationKey])

        return true
}

func application(application: UIApplication,
    openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool {
        var options: [String: AnyObject] = [UIApplicationOpenURLOptionsSourceApplicationKey: sourceApplication!,
            UIApplicationOpenURLOptionsAnnotationKey: annotation]
       GIDSignIn.sharedInstance().handleURL(url,
            sourceApplication: sourceApplication,
            annotation: annotation)
        let handled = FBSDKApplicationDelegate.sharedInstance().application(application, openURL: url, sourceApplication: sourceApplication, annotation: annotation)

         return  handled
}
func signIn(signIn: GIDSignIn!, didSignInForUser user: GIDGoogleUser!,
    withError error: NSError!) {
        if let error = error {
            print(error.localizedDescription)
            return
        }
        // ...

func signIn(signIn: GIDSignIn!, didDisconnectWithUser user:GIDGoogleUser!,
    withError error: NSError!) {
        // Perform any operations when the user disconnects from app here.
        // ...
        }

}
                                        //
         }

和我的loginViewController:

func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!) {
    print("RESULT : (result)")
    print("ERROR : (error)")
    let credential = FIRFacebookAuthProvider.credentialWithAccessToken(FBSDKAccessToken.currentAccessToken().tokenString)
    FIRAuth.auth()?.signInWithCredential(credential, completion: {
    (user, error) in
        if error != nil{
            self.signInButton.enabled = true
            print("Problem at signing in with facebook with error : (error)")
            self.showAlert("Error Signing in With Facebook", message: "Please enter the correct email and password")

        }else {
        print("USER LOGGED IN THROUGH FACEBOOK")
            _ = self.ref.child("users").observeEventType(FIRDataEventType.Value, withBlock: { (snapshot) -> Void in
                let usersDict = snapshot.value as? [String : AnyObject]
                print(usersDict)
                if let userDetails = usersDict![user!.uid] as? [String : AnyObject], let _ = userDetails["username"] as? String
                {
                    let homePageScene = self.navigationController?.storyboard?.instantiateViewControllerWithIdentifier("HomePageViewControllerVC_ID") as! HomePageViewController
                    self.navigationController?.pushViewController(homePageScene, animated: true)
                }
                else{
                    let userNamePageScene = self.navigationController?.storyboard?.instantiateViewControllerWithIdentifier("UsernameViewControllerVC_ID") as! UsernameViewController
                    self.navigationController?.pushViewController(userNamePageScene, animated: true)
                }
            })
        }
    })
}

我是个新手…感谢任何帮助!!

要检索providerData,您现在需要这样做。

if let user = user {
} else {
print("User cancelled the Facebook login"))
}

您需要检查是否有用户,或者用户是否取消了登录。这样的:

if let user = FIRAuth.auth()?.currentUser {
for profile in user.providerData {
let providerId = profile.providerId
let uid = profile.uid;  // Provider-specific UID
let name = profile.displayName
let email = profile.email
let photoUrl = profile.photoURL
}
} else {
// No user logged in.
}

func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError?) {
if let error = error {
    print(error.localizedDescription)
    return
}
self.performSegueWithIdentifier("login", sender: self)
}

或其他一些补充:

let currentToken = FBSDKAccessToken.currentAccessToken()
// Show login if this is first time logging in
if (currentToken == nil || !currentToken.hasGranted("email")) {
    let ref = Firebase(url: "https://my-app.firebaseio.com")
    let facebookLogin = FBSDKLoginManager()
    facebookLogin.logInWithReadPermissions(["email"], fromViewController: self, handler: {
        (facebookResult, facebookError) -> Void in
        if facebookError != nil {
            log.error("Facebook login failed. Error (facebookError)")

最新更新