Categories: iOSSwiftTutorials

Login with Instagram in iOS

Today, I decided to write about Instagram’s login integration which is really a pain in the neck to integrate but thanks to Shyam Bhat for developing InstagramKit which makes things simple for us. So without further ado lets get started.

First of all like any other social networking website, we’ll have to create an app on Instagram’s Developer portal. Follow the steps below to create an app to get Client ID.

  • Click on Manage Clients and Sign Up for the Developer Signup.

 

  • After providing the required information you’ll be redirect to this screen, click on Register Your Application.

 

  • Submit the given fields and don’t forget to add a valid Redirecting Url, it’s required to redirect user after the user has successfully logged in. Privacy Policy URL is important, when you’ll be submitting Permissions‘ request your app’s website needs to have a Privacy Policy in order to complete that form (more on Permissions is covered below).
  • Then after submitting your app details, you can get your Client ID. Click on Manage button.
  • then Click on Security tab, and uncheck Disable implicit OAuth and check Enforce Signed Requests. You’ll get an “Implicit authentication is disabled.” error when you try to run the app otherwise.

 

  • Afterwards click on Permissions tab.

Everything here is all set and good to go, Create a Podfile for your project and install the following libraries.

pod 'InstagramKit', '~> 3.0'
pod 'InstagramKit/UICKeyChainStore'

After that open up your info.plist, add InstagramAppClientId and InstagramAppRedirectURL. Paste your Client ID and make sure that you enter the exact same Redirect URL that you provided when creating the app on Instagram’s Developer portal.

Now open up your project and drag a UIViewController and place a UIWebView on top of it, and connect its delegate.

 

In your ViewController class, create an outlet of the UIWebView you just added to the controller, and import InstagramKit at the top. Your class should look something like this.

import UIKit
import InstagramKit



class ViewController: UIViewController {

    @IBOutlet weak var webView: UIWebView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //load request in the webView
        let auth = InstagramEngine.shared().authorizationURL()
        self.webView.loadRequest(URLRequest(url: auth))
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
}

Now its time to implement UIWebViewDelegate, in which we’ll get our access token.

extension ViewController: UIWebViewDelegate{
    
    //MARK: WebView Delegate
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        do {
            if let url = request.url {
                if (String(describing: url).range(of: "access") != nil){
                    try InstagramEngine.shared().receivedValidAccessToken(from: url)
                    //If successfully logged in, Access token can be get from here
                    if let accessToken = InstagramEngine.shared().accessToken {
                        print("accessToken: \(accessToken)")
                        
                        
                    }
                }
            }
        } catch let err as NSError {
            print(err.debugDescription)
        }
        return true
    }
    
    
}

Now run your app, and type in your username and password then login.

 

When you’re successfully logged in, you’ll get an access token printed in your console log and will be redirected to your Redirect URL. In my case it was kodesnippets.com.


If you want to get basic user information.

func getUserDetails(){
    
        InstagramEngine.shared().getSelfUserDetails(success: { (user) in
            print("User:\(user.fullName ?? "")\nProfile:\(user.profilePictureURL?.absoluteString ?? "")")
            
        }, failure: { (error, code) in
          print(error.localizedDescription)
        })
    
 }

But again it will only work when you have submitted the request for the Permission, or else you’ll get a Request failed: forbidden (403) error.

Code can be found here.
So that’s all for this tutorial folks.
See you in the next one. 🙂
Peace.

 

Aaqib Hussain

Aaqib is an enthusiastic programmer with the love of Swift and anything that looks like Swift i.e Kotlin. He loves writing code in Swift, and exploring new technology and platforms. He likes to listen to old music. When he is not writing code, he's probably spend his time watching movies, tv-shows or anime, or either doing some research for writing the next article. He started Kode Snippets in 2015.

View Comments

  • I'm really enjoying the theme/design of your website.

    Do you ever run into any internet browser compatibility problems?
    A handful of my blog visitors have complained about my site not operating correctly in Explorer but looks great in Chrome.
    Do you have any tips to help fix this issue?

    • I don't really have any idea about that, I think it depends on the theme that you're using.

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