-->

How can I do a Facebook login using Swift 2.0 and

2020-06-04 16:02发布

问题:

I have added the latest Facebook SDK to my XCode 7.1 project written for iOS 9.1. Unfortunately all I know is Swift, not Objective C. Facebook's developer site documentation only has the documentation in Objective C. Every search on Google reveals documentation that is just too old because things have changed so much just in the past 6 months. So I'm kind of lost.

I did all the easy stuff with the plist file.

I was able to use:

import FBSDKCoreKit
import FBSDKLoginKit

I also added:

return FBSDKApplicationDelegate.sharedInstance().application(application, openURL: url, sourceApplication: sourceApplication, annotation: annotation)

and

return FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)

To my AppDelegate.swift file. This all works and builds successfully. I have the correct frameworks added as well, obviously. Beyond this point I'm at a standstill because I don't know the syntax for adding a login button, for capturing what I assume would be returned json strings with tokens and other profile information I can use to store in the user's account, etc.

回答1:

You're on the right track.

Have you set up your pList yet?

You're gonna have to add to your VC, add a login button, deal with delegate, and then deal with FB info. Something like (but not exactly) this:

class yourVC: UIViewController, FBSDKLoginButtonDelegate, UITextFieldDelegate 

{
var loginView : FBSDKLoginButton = FBSDKLoginButton()

viewDidLoad() {
            loginView.frame = CGRectMake(20, 20, theWidth-40, 40)
            self.view.addSubview(loginView)
            loginView.readPermissions = ["public_profile", "email", "user_friends","user_birthday"]
            loginView.delegate = self

}

func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!) {
        if ((error) != nil)
        {
        //handle error
        } else {
                returnUserData()
        }
    }

func returnUserData()
    {


  let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"id,interested_in,gender,birthday,email,age_range,name,picture.width(480).height(480)"])
    graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in

        if ((error) != nil)
        {
            // Process error
            print("Error: \(error)")
        }
        else
        {
            print("fetched user: \(result)")
            let id : NSString = result.valueForKey("id") as! String
            print("User ID is: \(id)")
            //etc...
         }
      })
}

You're gonna have to play around with the returnData() part to get it right, but this code should get you 90% of the way there.

I've included a wide range of permissions (user age, interested in, etc), but you'll have to configure them yourself. Honestly this part (the hard part) is really similar with it's object C counterpart, which is much better documented. Just download some get projects where it's working, and try to parse them together into something that suits your fancy.

It can be hard to get it all working, but give it a go, and keep at it!



回答2:

If you want to perform login from Facebook on click of your custom button, this will help:

@IBAction func onClickFacebookButton(sender: UIButton){
    let login = FBSDKLoginManager()
    login.loginBehavior = FBSDKLoginBehavior.SystemAccount
    login.logInWithReadPermissions(["public_profile", "email"], fromViewController: self, handler: {(result, error) in
        if error != nil {
            print("Error :  \(error.description)")
        }
        else if result.isCancelled {

        }
        else {
            FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "first_name, last_name, picture.type(large), email, name, id, gender"]).startWithCompletionHandler({(connection, result, error) -> Void in
                if error != nil{
                    print("Error : \(error.description)")
                }else{

                    print("userInfo is \(result))")

                }
            })
        }

    })
}