解析 Facebook Login/Signup 不工作 (Swift)

Parse Facebook Login/Signup Not Working (Swift)

一个多月以来,我一直在尝试使用 Swift 在我的应用程序中实现 Parse 的 Facebook 登录功能,但似乎无法弄明白,这让我很沮丧。我成功地将我的应用程序分别链接到 Facebook 和 Parse,但我无法使用 Facebook 的登录名创建 Parse 用户。我相信 AppDelegate 设置正确,所以我只会显示我的 LoginViewController,希望知道他们在做什么的人可以帮助我:

import UIKit
import Parse
import FBSDKCoreKit
import FBSDKLoginKit


protocol LoginViewControllerDelegate {
func onRegister(loginViewController : LoginViewController)
func onFacebookLogin(loginViewController : LoginViewController)
func onLogin(loginViewController : LoginViewController)
}


class LoginViewController: UIViewController, FBSDKLoginButtonDelegate {

//MARK: - Outlets

@IBOutlet weak var lblStatus: UILabel!

//var delegate : LoginViewControllerDelegate?

// Set permissions required from the facebook user account
let permissions = [ "user_about_me", "user_relationships", "user_location", "user_birthday", "public_profile", "user_friends", "user_email", "user_gender"]

//MARK: - Initial Load

override func viewDidLoad() {
    super.viewDidLoad()

    self.lblStatus.alpha = 0

    //Facebook
    if (FBSDKAccessToken.currentAccessToken() != nil)
    {
        // User is already logged in, do work such as go to next view controller.
    }
    else
    {
        let loginView : FBSDKLoginButton = FBSDKLoginButton()
//            self.view.addSubview(loginView)
//            loginView.center = self.view.center
//            loginView.readPermissions = ["public_profile", "email", "user_friends"]
        loginView.delegate = self
    }

    // ---------------------------- Check if user is logged in ---------------------
    if PFUser.currentUser() != nil {
        println("parse: User already logged in")
        performSegueWithIdentifier("loggedIn", sender: self)
    }

}

//MARK: - Facebook Login Button

func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!) {

    if ((error) != nil) {
        println(error) // Process error
    } else if result.isCancelled { // Handle cancellations
    } else {
        // If you ask for multiple permissions at once, you
        // should check if specific permissions missing
        if result.grantedPermissions.contains("email")
        {
            // Do work
        }
    }
    returnUserData()
}

@IBAction func facebookLoginDidPress(sender: AnyObject) {

    self.lblStatus.alpha = 0
    PFFacebookUtils.logInInBackgroundWithReadPermissions(self.permissions, block: {
        (user: PFUser?, error: NSError?) -> Void in
        if (user == nil) {
            if (error == nil) {
                println("User cancelled FB login")
                self.lblStatus.alpha = 1
            }else{
                println("FB login error: \(error)")
                self.lblStatus.alpha = 1
            }
        } else if user!.isNew {
            println("User signed up and logged in with Facebook! \(user)")
            self.requestFacebook()
            self.returnUserData()
            self.performSegueWithIdentifier("loggedIn", sender: self)
        } else {
            println("User logged in via Facebook \(user)")
            self.performSegueWithIdentifier("loggedIn", sender: self)
        }
    })

}

func requestFacebook() {

    let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: nil)
    graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in

        if ((error) != nil)
        {
            // Process error
            println("Error: \(error)")
        }
        else if error == nil
        {

            var userData: NSDictionary = NSDictionary(objectsAndKeys: result)

            var facebookID: AnyObject? = userData["id"]
            var name: AnyObject? = userData["first_name"]
            var gender: AnyObject? = userData["gender"]
            var birthday: AnyObject? = userData["birthday"]

            var pictureURL = "https://graph.facebook.com/\(facebookID)/picture?type=large&return_ssl_resources=1"

            var URLRequest = NSURL(string: pictureURL)
            var URLRequestNeeded = NSURLRequest(URL: URLRequest!)


            NSURLConnection.sendAsynchronousRequest(URLRequestNeeded, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse!,data: NSData!, error: NSError!) -> Void in
                if error == nil {
                    var picture = PFFile(data: data)
                    PFUser.currentUser()!.setObject(picture, forKey: "profilePicture")
                    PFUser.currentUser()!.saveInBackground()
                }
                else {
                    println("Error: \(error.localizedDescription)")
                }
            })
        }
    })
}

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
        {
            if let userName : NSString = result.valueForKey("name") as? NSString {
                println("User Name is: \(userName)")

            } else {println("No username fetched")}

            if let userEmail : NSString = result.valueForKey("email") as? NSString {
                println("User Email is: \(userEmail)")
            } else  {println("No email address fetched")}

            if let userGender : NSString = result.valueForKey("gender") as? NSString {
                println("User Gender is: \(userGender)")
            } else {println("No gender fetched") }
        }
    })
}
}

一些重要的注意事项:

  1. 我使用的是最新版本的 Parse (1.7.4) 和 FBSDK (4.1),所以我在网上找到的大多数其他方法都不再有效,因为某些函数或成员已被删除从那时起。

  2. "func loginButton" 是我用于 FBSDKLoginButton 的,而“@IBAction func facebookLoginDidPres”是用于我尝试用于登录的常规 UIButton。基于我所拥有的最近了解到,我相信 UIButton 方法是我应该使用的方法,但该方法会导致线程 1:信号 SIGABRT 错误说明:

由于未捕获的异常 'NSInvalidArgumentException' 而终止应用程序,原因:'+[PFFFacebookUtils logInInBackgroundWithReadPermissions:block:]:无法识别的选择器发送到 class 0x10ed3ed80' *** 首先抛出调用栈:

...

libc++abi.dylib: 以 NSException 类型的未捕获异常终止 (lldb)“”

所以我放置了一个异常断点,它在我的 IBAction 中的 "logInInBackgroundWithReadPermissions" 函数末尾结束,控制台显示:

"[PFFFacebookUtils logInInBackgroundWithReadPermissions:block:]: 无法识别的选择器发送到 class 0x10dbe2db0 (lldb)"

  1. 我觉得最后一个值得一提的细节是,当我 运行 应用程序时,我的控制台状态为 "parse: User already logged in",但是当我检查 Parse 时没有创建用户。这是从我的 LogInViewController 的 viewDidLoad 函数的 "check if the user is logged in" 部分下的部分打印出来的。

我将永远感谢任何能帮助我解决这个困扰我太久的问题的人。提前致谢!

我删除了旧的 PFFFacebookUtils 框架,但保留了 PFFFacebookUtilsV4 框架,这解决了我的问题!希望这可以帮助其他人解决这个问题:)

我也有同样的问题,我的解决办法是定义Login behavior = Web

PFFacebookUtils.facebookLoginManager().loginBehavior = FBSDKLoginBehavior.Web

当我在调用 loginInBackground... 之前调用它时,在单击 "OK" 按钮后,我的应用程序收到了用户的回调(不是零)并且 PFUser.currentUser 已更新用户。