Tuesday, November 17, 2015

Overview

This is a quick post on how to integrate Facebook Login with your app in swift. I followed a video tutorial from VeaSoftware on integrating the Facebook login button and I highly recommend it. This post will be a summary of his video.

Content

Step 1

Download the Facebook SDK




Step 2

Add the Facebook SDK to your Xcode Project like this. Make sure to uncheck “Copy items if needed”.

Drop




Step 3

Configure XCode with the new .plist entries.

  1. In Xcode right-click your .plist file and choose “Open As Source Code”.
  2. Copy & Paste the XML snippet into the body of your file (<dict>...</dict>).
  3. Replace:
    • fb{your-app-id} with your Facebook App ID and the prefix fb. E.g.: fb123456.
    • {your-app-id} with your Facebook App ID.
    • {your-app-name} with the Display Name you configured in the app dashboard.
1
2
3
4
5
6
7
8
9
10
11
12
13
<key>CFBundleURLTypes</key>
<array>
  <dict>
    <key>CFBundleURLSchemes</key>
    <array>
      <string>fb{your-app-id}</string>
    </array>
  </dict>
</array>
<key>FacebookAppID</key>
<string>{your-app-id}</string>
<key>FacebookDisplayName</key>
<string>{your-app-name}</string>




Step 4

If you’re using iOS 9, read this.




Step 5

Supply Facebook with your Bundle Identifier




Step 6

Now to the fun part. This is this code that will display the button.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import UIKit
import FBSDKCoreKit
import FBSDKLoginKit

class LoginViewController: UIViewController, FBSDKLoginButtonDelegate {
    override func viewDidLoad() {
        super.viewDidLoad()

        if (FBSDKAccessToken.currentAccessToken() == nil) {
            print("Already logged in")
        } else {
            createAndDisplayLoginButton()    
        }
    }

    func createAndDisplayLoginButton() {
        let loginButton = FBSDKLoginButton()
        loginButton.readPermissions = ["public_profile", "email", "user_friends"]
        loginButton.center = self.view.center
        loginButton.delete = self

        self.view.addSubview(loginButton)
    }


    // MARK: - Facebook events

    func loginButton(loginButton: FBSDKLoginButton!, 
                didCompleteWithResult result: FBSDKLoginManagerLoginResult!, 
                error: NSError!) {
        if (error == nil) {
            print("Logged in")
        } else {
            print(error.localizedDescription)
        }
    }

    func loginButtonDidLogOut(loginButton: FBSDKLoginButton!) {
        print("User logged out")
    }
}

Random Posts