Twitter Login Integration In iOS Using Swift

Hi, In this post, we'll learn how to integrate Twitter SDK in iOS apps. Its pretty simple and easy to implement Login using Twitter in iOS applications. You can learn it just by going through this post only once. I hope you'll like it!

FYI, we can use twitter login in 2 ways in our iOS applications. One is using default Twitter Login Button and second one is using our own custom button for twitter login. In this post, I'll guide you through both the twitter login methods.

Without any delay, let's start with our project setup. Again, we'll accomplish our goal by following a step by step approach as mentioned below:
  1. Setup Xcode Project
  2. Install Twitter Pods
  3. Create App On Twitter Apps Dashboard
  4. Write Some Code
  5. Run Our App
STEP 1: Setup Xcode Project: 

First of all, open your Xcode project and create a single view application. Give some name to your project and click Next.

Here, if you want to use Twitter's own custom Login button then there's no need to add a custom button to your project but If you want to add your own login button then just add it by dragging and dropping a button on your storyboard. Give it some name like "Login With Twitter". Add some constraint on this button and create its action in your ViewController.swift file. After this, close your Xcode project, it's time to move to step number 2.

STEP 2: Install Twitter Pods

For installing Twitter pods into your project, fire up the terminal and go to your project directory by giving following command in the terminal:

cd <path of your project> 

Example: cd /users/Bhanu/Desktop/Projects/TwitterLoginDemo

Now give one more command

pod init

This command will create a pod file in your project folder. In this file, you need to write:

    pod 'TwitterKit'

After saving this, your file will look like this:

Now, run this command in your terminal:

pod install

This is going to take some time to install the required twitter pods in your project. So, wait for some time. Further, run below command just to ensure that you're using the latest pod versions.

pod update TwitterKit

Once all this setup is done, close the terminal and go to your projects folder. Reopen your project and make sure to open .xcworkspace instead of .xcodeproj

STEP 3: Create App On Twitter Apps Dashboard
Here in this step, we'll create our Twitter app on twitter apps dashboard. So, just open your browser and go to this link: Twitter Apps Dashboard

Here just follow the simple steps and register your new app on Twitter's Application Management console. You can follow below mentioned steps to create your new twitter app:
  • Click on "Create New App"
  • Enter Application Details and click on "Create Your Twitter Application"
  • Go to permissions tab
  • Choose, "Read, write and Access direct messages".
  • Check, "Request email address from users"
  • Click "Update Settings"
  • In your app's setting, don't forget to add "Callback URL", "Privacy Policy URL", "Terms of Service URL". Make sure to use a valid URLs or you can use any placeholder URLs (eg. "http://placeholder.com") 
  • Update Settings again
  • Done.
Now, you'll get the Consumer Key and Consumer Secret Key for your application as shown below:

After creating your app and following all the steps, don't forget to add below provided XML code in your app's info.plist file in the Xcode. For this, just click on your info.plist file and select Open as a Source Code. Now, just after the <dict> tag, insert the following XML snippet into it:
        
        <key>CFBundleURLTypes</key>
        <array>
            <dict>
                <key>CFBundleURLSchemes</key>
                <array>
                    <string>twitterkit-<consumerKey></string>
                    </array>
                </dict>
            </array>
            <key>LSApplicationQueriesSchemes</key>
            <array>
                <string>twitter</string>
                <string>twitterauth</string>

            </array>

Here, replace the consumerKey with your own consumer key(Twitter API key) which you get in your Twitter application dashboard for your newly created app.

STEP 4: Write Some Code

Now, open your AppDelegate.swift file and add following line of code in its first application function i.e.

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        
        Twitter.sharedInstance().start(withConsumerKey:"gu2dsasdsaTxasObYidfjsfux", consumerSecret:"ZasdasdfhgXcyPP0e5yrjNcsdffjshhabwh23xqlDbhjlfhUdd")
        
        return true
    }

Also add one more function here:

    func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {

        return Twitter.sharedInstance().application(app, open: url, options: options)

    }



Once all this done, let's jump over to the ViewController.swift file.

Here, we've 2 ways to implement Twitter Login. 



1. Using Default Twitter Login Button: This is the simplest way to add twitter login in iOS applications. Just add following lines of code in your viewDidLoad() method:



        let logInButton = TWTRLogInButton(logInCompletion: { session, error in
            if (session != nil) {
                print("signed in as \(String(describing: session?.userName))");
                print("userID \(String(describing: session?.userID))");
                print("authToken \(String(describing: session?.authToken))");
               
            } else {
                print("error: \(String(describing: error?.localizedDescription))");
            }
        })
        
        logInButton.center = self.view.center
        self.view.addSubview(logInButton)
        

2. Using Custom Login Button: Just add one custom button on your view controller and add following code in your action button's method:



        Twitter.sharedInstance().logIn(completion: { (session, error) in
            if (session != nil) {
                print("signed in as \(String(describing: session?.userName))");
            } else {
                print("error: \(String(describing: error?.localizedDescription))");
            }
        })



STEP 5: Run Your App

Once all this done, run your app and you'll get the following screen on your device:
Twitter Login Button Screen
After successful login, you'll get the user's name, ID, token etc. printed in your console which you can use further as per your own app requirements. 

Here’s the full code for your reference:


If you've any doubts or need any further help, then do message me in the comments section below and I'll try to respond you as soon as possible.

Thanks for your time and keep coding.. 👨‍💻

Comments

Popular posts from this blog

PayPal Integration In iOS Applications | Payment Gateways iOS/Swift

How To Parse JSON Data In iOS (Swift 3 + Xcode 8) ?

UI Date Picker For UI Text Field With UI Tool Bar (Swift 3 + Xcode 8)