Categories: Swift Programming

Facebook Login integration with Custom Button in iOS

Hello guys!
Today I’m going to show you how to integrate Facebook login to your iOS app using Swift.

Login to your Facebook and go to developers.facebook.com.

Click “My Apps” and click “Add a New App”

Name the app and select the suitable category then click Create App ID.

YOU SHALL NOT PASS!!!. 😀

You’ll be redirected to this page. Click Choose a Platform.

You’ll then reach here. Click iOS.

Download the SDK from here.

Open your project’s info.plist as Source Code.

Paste all the .plist code from this page to your .plist.

Your final info.plist will look something like this

Finally at the end of the page, paste your Bundle identifier, then click next.

Open your project and Unzip FacebookSDK folder and drag FBSDKCoreKit.framwork and FBSDKLoginKit.framework into your project.

Since our environment is all setup. Now It’s time to role sleeves and start code.

Open your AppDelegate, import FBSDKCoreKit and FBSDKLoginKit and paste the following code.

//This goes in your DidFinishLaunchingWithOptions
FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)

func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool {
return FBSDKApplicationDelegate.sharedInstance().application(application, openURL: url, sourceApplication: sourceApplication, annotation: annotation)
}

Your AppDelegate should look like this

.

Now add two View Controllers and embed a Navigation Controller to it.
Drag a button to the first View Controller and name it as LOGIN and create an action event for it. Drag a segue from root view controller to its embedded view controller and name it as “login”.

In our viewDidLoad we need to enable the listener that will provide us all the credentials of the logged in user.

FBSDKProfile.enableUpdatesOnAccessTokenChange(true)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "profileUpdated:", name: FBSDKProfileDidChangeNotification, object: nil)

and the selector event for this.

func profileUpdated(notification: NSNotification) {

if FBSDKAccessToken.currentAccessToken() != nil{
let name = FBSDKProfile.currentProfile().name
let uid = FBSDKProfile.currentProfile().userID
let fname = FBSDKProfile.currentProfile().firstName
let lname = FBSDKProfile.currentProfile().lastName
let pplink = FBSDKProfile.currentProfile().imageURLForPictureMode(FBSDKProfilePictureMode.Square, size: CGSize(width: 400,height: 400))

print("name:(name)")
print("User ID:(uid)")
print("first(fname)")
print("last:(lname)")
print("image:(String(pplink))")
self.getUserEmail()
}
else {

print("logged out")

}
}

You’ll get full name, first name, last name, and profile picture. In order to get the email. We need to do a graph request.

func getUserEmail()
{
let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters:["fields": "email"], HTTPMethod: "GET")
graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in

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

let userEmail : NSString = result.valueForKey("email") as! NSString
let email = userEmail as String
print("Email:(email)")
}
})
}

 

Now, In your login button event.

@IBAction func loginButton(sender: AnyObject) {

let login: FBSDKLoginManager = FBSDKLoginManager()
login.logInWithReadPermissions(["public_profile","email","user_friends"], fromViewController: self) { (result: FBSDKLoginManagerLoginResult!, error) -> Void in

if ((error) != nil)
{
// Process error
}
else if result.isCancelled {
// Handle cancellations

}
else {

self.performSegueWithIdentifier("login", sender: nil)

}

}
}

 

Create an action of argument type UIStoryboardSegue in your root view controller so that you can perform an unwind segue when you logout.

@IBAction func returnOnLogout(storyboard: UIStoryboardSegue){

}

 

Add a new class for the second view controller, add a button to it and rename it as Logout and create an action for it.

@IBAction func logout(sender: AnyObject) {

if FBSDKAccessToken.currentAccessToken() != nil {
let logout = FBSDKLoginManager()
logout.logOut()

}
}


Hold ctrl on your button and drag it all the way to Exit responder and also hide the navigation bar.

self.navigationItem.hidesBackButton = true

Save and run the app. You’ll get the following results.

I hope that it would have helped.
Here is the source code for this on Github.

Sayonara!

Aaqib Hussain

View Comments

Recent Posts

Things to know when moving to Germany

This article covers some important things you must know when you are considering a move…

3 years ago

Unit Testing in Android for Dummies

What is Unit Testing? In its simplest term, unit testing is testing a small piece…

4 years ago

Factory Design Pattern

In this article, you will learn about a type of Creational Design Pattern which is…

5 years ago

Creating Target specific Theme in iOS

In this tutorial, you will go through the use of targets to achieve two separate…

5 years ago

Facade Design Pattern

In this article, you will learn about a type of Structural Design Pattern which is…

5 years ago

Singleton Design Pattern

In this article you will learn about a type of Creational Design Pattern which is…

5 years ago