Parse Tutorial: Adding a Twitter/Facebook Signup/Login to Your iOS App

Published Sep 03, 2015Last updated Apr 12, 2017
Parse Tutorial: Adding a Twitter/Facebook Signup/Login to Your iOS App

The full code for this Tutorial can be found at https://github.com/mattgoldspink/swift-parse-login-part1

First impressions are everything, so when users download your app, you have to make sure that the first screen they see lets them know this app means business. Setting up a proper signup/login process used to be very tedious and time-consuming. Now you can kiss those long hours spent on setting up the login screen goodbye thanks to Parse, which offers a great platform to handle signups and integration with Facebook and Twitter for free.

In this tutorial, we’ll look at how to setup a custom Login and Signup view, so you can get users signed up with minimal effort. I will show you how to get all the configuration setup using Parse’s default Login and Signup views. Once you have completed the setup, check out Part 2 of my Parse tutorial to see how we can customize the styles to make your app really stand out!

For the purpose of our tutorial, we’re going to create a social network called “Vay.K" for people who want to share photos from their vacations.

1) Setting Up Our Project in XCode

First create a new project in Xcode

The one thing that we need to note here is the Bundle Identifier - in my case it’s com.mattgoldspink.VayK

2) Setup Your App on Parse, Facebook and Twitter

Go to www.parse.com and sign up for an account. Once you’re logged in go create a new app.

Once your app is created click on the Cog in the top right and choose Settings. On this next screen choose Authentication from the menu on the left and you’ll see the following:

Now we need to go and set up a Facebook App.

Head to http://developer.facebook.com and sign up as a developer. Again, once you’re logged in, go ahead and add a new app.

Be sure to pick iOS as the platform

Enter your app name and click Create New Facebook App ID

Pick your app category and Create App ID

On the next page, you’ll be presented with setup instructions. Skip straight down to Configure your info.plist. You’ll need to copy the XML snippet they give you and add it into the bottom of your info.plist (it should be in the Supporting Files folder in Xcode). Make sure to right click it and choose Open As Source Code.

On the same page scroll down and you’ll see Supply us with your Bundle Identifier - fill this in with your project’s Bundle Identifier

With this done, scroll all the way back to the top of this page and click Skip Quick Start. You should now be able to see your App ID and App Secret (click Show)

Head back over to Parse where we left off, and fill in the blanks for Facebook Auth. If all goes well when you add them, you should see a nice blue tick next to it.

Now it's time to setup Twitter!

Go to https://apps.twitter.com and sign in with your Twitter Account. Once logged in, choose to Create New App

Next, fill in the app details. It’s important for the Callback URL to be filled in with something, even though it isn’t marked as a mandatory field. Check the developer agreement and then click Create your Twitter application

Once that is done, you’ll be presented with the App Details screen from which you can copy the Consumer Key (API Key)

And finally let’s jump back to Parse.com and fill in our missing Twitter piece - again if it’s all good then you’ll get a nice blue tick.

3) Set Up the CocoaPods with Parse, Facebook and Twitter

I recommend using CocoaPods to manage the dependencies. If you haven’t used it before you’ll need to install it. Open a Terminal and type:

$ sudo gem install cocoapods

Now in Xcode add a new Empty file to your project called Podfile

Inside of that paste the following:

platform :ios, '8.1'

xcodeproj 'VayK'

target :VayK, :exclusive => true do
    pod 'Parse'
    pod 'ParseUI'
    pod 'ParseFacebookUtilsV4'
    pod 'ParseTwitterUtils'
    pod 'FBSDKCoreKit'
    pod 'FBSDKLoginKit'
end

Changing VayK to the name of your project. Switch back to your Terminal and navigate to the directory which contains your project and run:

$ pod install

Note you need to run this in the directory where the Podfile we created lives

This will create a whole new Xcode workspace for you, so first close your project in Xcode, then re-open XCode with the file named <your project name>.xcworkspace. While opening this, you should find both your original project and a new one called Pods

This second project includes all the dependencies we just listed in the Podfile ready for us to use! The one last piece before we start churning out code is to create a bridging header so that these Objective-C frameworks can be used by Swift.

Inside your project, create a new Cocoa Touch file. Make sure it’s an Objective-C file (NOT a Swift file). When you come to save, you’ll be issued a prompt asking if you want to configure an Objective-C Bridging Header - choose YES. Then delete the .m and .h file that were added and jump straight to the new file at the bottom of your project which should be called something like VayK-Bridging-Header.h

Open it up and paste in the following:

#import <Parse/Parse.h>
#import <ParseUI/ParseUI.h>
#import <ParseFacebookUtilsV4/PFFacebookUtils.h>
#import <ParseTwitterUtils/ParseTwitterUtils.h>
#import <ParseUI/ParseUI.h>
#import <Bolts/Bolts.h>
#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import <FBSDKLoginKit/FBSDKLoginKit.h>

Quickly build and run the project and ensure there are no errors. You should see it compiles all the frameworks we installed using Cocoapods before it starts to compile your project. If it compiles and runs (you won’t see anything on the simulator yet), then we’re in great shape to start writing some real code!

4) Set Up Our AppDelegate

The first thing to do is to make sure we configure our connections to Parse, Facebook and Twitter, so that we can add the login and signup screens their servers can authenticate for our app. Firstly paste the following code into the AppDelegate.swift file:

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        Parse.setApplicationId(“<Your Parse Application ID>", clientKey:”<Your Parse Client Key>")
        PFTwitterUtils.initializeWithConsumerKey(“<Your Twitter Consumer Key>", consumerSecret:”<Your Twitter Consumer Secret>")
        PFFacebookUtils.initializeFacebookWithApplicationLaunchOptions(launchOptions);
        return true
    }

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

    func applicationDidBecomeActive(application: UIApplication) {
        FBSDKAppEvents.activateApp()
    }
   
}

The application:didFinishLaunchingWithOptions configures Parse. To get your Application ID and Client Key on the Parse.com page for your app, click Keys

Then we configure PFTwitterUtils to get the Consumer Key and Consumer Secret. To do this, go to your twitter app in the browser and click the Keys and Access Tokens tab

Notice how there are no keys for Facebook? Well, you actually did that earlier in step 2 when you edited the plist file. So here we can now just initialize PFFacebookUtils with any launch options.

In the AppDelegate, we also add 2 other hooks for Facebook. The first is application:openUrl:sourceApplication:annotation. This function is called when we jump out to the Facebook app or Safari to log the user in and then re-enter the app. The second function applicationDidBecomeActive allows the Facebook SDK to track app usage.

5) Configuring Our ViewController to Launch the Login Screen

So in our ViewController we want to do the following for now:

  • Check if the user is already logged in. If so, for now we’ll just show an UIAlertView - in reality you’d launch the first screen of your app if the user is already logged in
  • If the user isn’t logged in, we’ll present a Login screen with options to login using an email address and password, Facebook, Twitter, or an option to sign up as a new User.

So let’s start - first paste the following into the ViewController.swift file:

class ViewController: UIViewController, PFLogInViewControllerDelegate {

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        if (PFUser.currentUser() == nil) {
            let loginViewController = PFLogInViewController()
            loginViewController.delegate = self
            self.presentViewController(loginViewController, animated: false, completion: nil)
        }
    }

}

Here we implement ParseUI’s PFLoginControllerDelegate. Then in the viewDidAppear we check if the currentUser() is empty and if so, we create an instance of the ParseUI PFLogInViewController, set our self as the delegate and present it. If you run the app you should see the following:

This is pretty cool, right? We hardly wrote any code and we already have a log in screen with a signup button (try it out!). But we want to customize this a little more:

  • We need the Facebook and Twitter log in buttons
  • Notice how it says Username/Password - I’m not a huge fan of keeping track of usernames, so we let users use their email address as their username.

To do this, we modify our viewDidAppear by adding the following two lines before presenting the view controller:

loginViewController.fields = .UsernameAndPassword | .LogInButton | .PasswordForgotten | .SignUpButton | .Facebook | .Twitter
 loginViewController.emailAsUsername = true
 self.presentViewController(loginViewController, animated: false, completion: nil)

The first line is the way to customize which fields/buttons PFLoginViewController will render in the View. Then, we tell Parse we want our users to simply use their email address as the username instead of having a separate username as well.

Running this now shows - this. Try logging in with Facebook or Twitter!

Notice how when you re-enter the app nothing happens? Let’s fix that so we show that the user is logged in using a simple UIAlertController.

Add a new function to your ViewController.swift to present a UIAlertController:

    func presentLoggedInAlert() {
        let alertController = UIAlertController(title: "You're logged in", message: "Welcome to Vay.K", preferredStyle: .Alert)
        let OKAction = UIAlertAction(title: "OK", style: .Default) { (action) in
            self.dismissViewControllerAnimated(true, completion: nil)
        }
        alertController.addAction(OKAction)
        self.presentViewController(alertController, animated: true, completion: nil)
    }

Now we need to call this from two places. The first is in viewDidAppear - if the user is already logged in, we can skip presenting the LoginViewController:

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        if (PFUser.currentUser() == nil) {
            ...
        } else {
            presentLoggedInAlert()
        }
    }

And the second place we need it is after the user logged in. For this we’ll implement our first PFLoginViewControllerDelegate method:

    func logInViewController(logInController: PFLogInViewController, didLogInUser user: PFUser) {
        self.dismissViewControllerAnimated(true, completion: nil)
        presentLoggedInAlert()
    }

Now if you relaunch the app, you should see the alert appear straight away because you just logged in (assuming you tried out the Facebook/Twitter buttons). Parse is smart enough to keep the user logged in for us! Now let’s pretend it's a fresh install by resetting the Simulator (use Reset Content and Settings in the iOS Simulator menu):

6) Adding Sign Up Logic to Our ViewController

Now we only have one piece missing- when using Sign Up button, nothing happens. To fix this we’ll make our ViewController.swift also implement the PFSignUpViewControllerDelegate protocol:

class ViewController: UIViewController, PFLogInViewControllerDelegate, PFSignUpViewControllerDelegate {

Now before we present the LoginViewController in viewDidAppear add our self as the delegate to the SignUpController:

loginViewController.signUpController?.delegate = self
self.presentViewController(loginViewController, animated: false, completion: nil)

And finally, implement the signUpViewController:didSignUpUser delegate method like so

    func signUpViewController(signUpController: PFSignUpViewController, didSignUpUser user: PFUser) {
        self.dismissViewControllerAnimated(true, completion: nil)
        presentLoggedInAlert()
    }

And you’re done!

Our final ViewController code is just short of 40 lines!

import UIKit

class ViewController: UIViewController, PFLogInViewControllerDelegate, PFSignUpViewControllerDelegate {

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        if (PFUser.currentUser() == nil) {
            let loginViewController = PFLogInViewController()
            loginViewController.delegate = self
            loginViewController.fields = .UsernameAndPassword | .LogInButton | .PasswordForgotten | .SignUpButton | .Facebook | .Twitter
            loginViewController.emailAsUsername = true
            loginViewController.signUpController?.delegate = self
            self.presentViewController(loginViewController, animated: false, completion: nil)
        } else {
            presentLoggedInAlert()
        }
    }
   
    func logInViewController(logInController: PFLogInViewController, didLogInUser user: PFUser) {
        self.dismissViewControllerAnimated(true, completion: nil)
        presentLoggedInAlert()
    }
   
    func signUpViewController(signUpController: PFSignUpViewController, didSignUpUser user: PFUser) {
        self.dismissViewControllerAnimated(true, completion: nil)
        presentLoggedInAlert()
    }

    func presentLoggedInAlert() {
        let alertController = UIAlertController(title: "You're logged in", message: "Welcome to Vay.K", preferredStyle: .Alert)
        let OKAction = UIAlertAction(title: "OK", style: .Default) { (action) in
            self.dismissViewControllerAnimated(true, completion: nil)
        }
        alertController.addAction(OKAction)
        self.presentViewController(alertController, animated: true, completion: nil)
    }
} 

7) What’s Next?

In the next tutorial, we’ll build on this and convert Parse’s default Login and Sign Up view’s to something any startup would be proud of!

If you need any help with anything found in this tutorial feel free to reach out to me on Codementor and I'd be happy to help!

The full code for this Tutorial can be found at https://github.com/mattgoldspink/swift-parse-login-part1

Discover and read more posts from Matt Goldspink
get started
Enjoy this post?

Leave a like and comment for Matt

28Replies
Hubert Jason
a year ago

Tutorial is very helpful

Manish Gautam
a year ago

Hi,
With parse moving to Parse-Server, when i am trying to login using Facebook, i see no action happening. I followed the guide step-by-step, but it doesn’t work.

In one of the steps you have mentioned about registering the FB keys to Parse, under “Facebook Applications”. Now with parse-server i can’t seem to add them anywhere. Would that affect it from logging in?

Can you suggest what i might be missing?

Also,
Same thing happens with Twitter login. i see no action being performed at all. Is there no more support for FB and Twitter login?

vivek
2 years ago

I think in
link : https://github.com/mattgold…
parse pod file is missing .

Show more replies

Get curated posts in your inbox

Read more posts to become a better developer