Skip to main content

How to Integrate Instagram login in iOS app using Swift3 -Tutorial

Integrate Instagram login in Swift




Integrate Instagram in ios swift3

Introduction to the post Integrate Instagram login in iOS app in Swift/Swift3

Instagram is the popular app that allows user to share pictures and small videos with their followers and people around the world. In iOS app, developers  can utilise Instagram Api in two ways

1) Login to the app using Instagram credentials
2) Share picture from the app to Instagram

If you are looking for objective c version then please check integrate Instagram in iOS objective C

Register your app with Instagram.

Now Instagram requires developer to submit there app for approval as like Facebook. Developers have to build their app in sandbox mode and when they want to go to the stores, they need approval from Instagram so that their could work in live environment.

Follow the steps to register your app with Instagram,

1) Login to https://www.instagram.com/developer/

2)  Click on Register client, by clicking on Register Your Application button (shown in image below)

 3) If you had created apps before this one then you have to click "Register a new client"

4) Fill in all the details under "Details" tab and under "Security" tab uncheck "Disable implicit oAuth" option. This will tell Instagram that we are using unsigned login approach. Signed login approach will be covered in separate tutorial.

UnCheck_Disable_implicit_OAuth

5) Click Register, to confirm your app registration with Instagram.

6) As soon as you register app,  you will be navigated to page where all your apps are listed. Click on manage button so that you can get client-secret for your app. 

Code to login with Instagram  in swift/swift3 language

I am not going to cover the app building from scratch, instead we will cover only Instagram-login View controller code.

First create a constant file as shown below

import Foundation

struct INSTAGRAM_IDS {

static let INSTAGRAM_AUTHURL = "https://api.instagram.com/oauth/authorize/"

static let INSTAGRAM_APIURl = "https://api.instagram.com/v1/users/"
static let INSTAGRAM_CLIENT_ID = "REPLACE_YOUR_CLIENT_ID_HERE"
static let INSTAGRAM_CLIENTSERCRET = "REPLACE_YOUR_CLIENT_SECRET_HERE"
static let INSTAGRAM_REDIRECT_URI = "REPLACE_YOUR_REDIRECT_URI_HERE"
static let INSTAGRAM_ACCESS_TOKEN = "access_token"
static let INSTAGRAM_SCOPE = "likes+comments+relationships"
}



Create an new UIViewController class and name it as InstagramLoginVC.  Open InstagramLoginVC.swift and declare our  UIWebView and  UIActivityIndicatorView IBOutlet's.

@IBOutlet weak var loginWebView: UIWebView!
@IBOutlet weak var loginIndicator: UIActivityIndicatorView!



Open your storyboard file or .xib file and drag, drop UIWebView and UIActivityIndicatorView to it. Connect IBOutlet's to both of the controls.

Open your InstagramLoginVC.swift class. First we will create a function named unSignedRequest(), which will make request to Instagram server

//MARK: - unSignedRequest
func unSignedRequest () {
let authURL = String(format: "%@?client_id=%@&redirect_uri=%@&response_type=token&scope=%@&DEBUG=True", arguments: [INSTAGRAM_IDS.INSTAGRAM_AUTHURL,INSTAGRAM_IDS.INSTAGRAM_CLIENT_ID,INSTAGRAM_IDS.INSTAGRAM_REDIRECT_URI, INSTAGRAM_IDS.INSTAGRAM_SCOPE ])
let urlRequest = URLRequest.init(url: URL.init(string: authURL)!)
loginWebView.loadRequest(urlRequest)
}


Now we call the above created unSignedRequest()  function in viewDidLoad()

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
loginWebView.delegate = self
unSignedRequest()
}



As you are seeing that we assigned UIWebView delegate to self in our viewDidLoad() function, it's time to implement UIWebViewDelegates

// MARK: - UIWebViewDelegate
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
return checkRequestForCallbackURL(request: request)
}
func webViewDidStartLoad(_ webView: UIWebView) {
loginIndicator.isHidden = false
loginIndicator.startAnimating()
}
func webViewDidFinishLoad(_ webView: UIWebView) {
loginIndicator.isHidden = true
loginIndicator.stopAnimating()
}
func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
webViewDidFinishLoad(webView)
}


In above code we implemented UIWebView delegates. Apart from shouldStartLoadWith delegate, rest are simply used to hide and show UIActivityIndicatorView.

In  shouldStartLoadWith delegate, we call a function named as checkRequestForCallbackURL() 
which accepts URLRequest as parameter. But still we did not write it's definition. So without wasting any time just write it

func checkRequestForCallbackURL(request: URLRequest) -> Bool {
let requestURLString = (request.url?.absoluteString)! as String
if requestURLString.hasPrefix(INSTAGRAM_IDS.INSTAGRAM_REDIRECT_URI) {
let range: Range<String.Index> = requestURLString.range(of: "#access_token=")!
handleAuth(authToken: requestURLString.substring(from: range.upperBound))
return false;
}
return true
}
func handleAuth(authToken: String) {
print("Instagram authentication token ==", authToken)
}



In checkRequestForCallbackURL() , we check for the URL returned by Instagram and if the URL has our REDIRECT URI as prefix then it means we have our access token/ Auth token in it and we have to extract it. At this moment we will stop our UIWebView to load new requests and extract extract it.

Complete code for UNSIGNED Instagram login request in swift/swift3  

import UIKit
class InstagramLoginVC: UIViewController, UIWebViewDelegate {
@IBOutlet weak var loginWebView: UIWebView!
@IBOutlet weak var loginIndicator: UIActivityIndicatorView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
loginWebView.delegate = self
unSignedRequest()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: - unSignedRequest
func unSignedRequest () {
let authURL = String(format: "%@?client_id=%@&redirect_uri=%@&response_type=token&scope=%@&DEBUG=True", arguments: [INSTAGRAM_IDS.INSTAGRAM_AUTHURL,INSTAGRAM_IDS.INSTAGRAM_CLIENT_ID,INSTAGRAM_IDS.INSTAGRAM_REDIRECT_URI, INSTAGRAM_IDS.INSTAGRAM_SCOPE ])
let urlRequest = URLRequest.init(url: URL.init(string: authURL)!)
loginWebView.loadRequest(urlRequest)
}
func checkRequestForCallbackURL(request: URLRequest) -> Bool {
let requestURLString = (request.url?.absoluteString)! as String
if requestURLString.hasPrefix(INSTAGRAM_IDS.INSTAGRAM_REDIRECT_URI) {
let range: Range<String.Index> = requestURLString.range(of: "#access_token=")!
handleAuth(authToken: requestURLString.substring(from: range.upperBound))
return false;
}
return true
}
func handleAuth(authToken: String) {
print("Instagram authentication token ==", authToken)
}
// MARK: - UIWebViewDelegate
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
return checkRequestForCallbackURL(request: request)
}
func webViewDidStartLoad(_ webView: UIWebView) {
loginIndicator.isHidden = false
loginIndicator.startAnimating()
}
func webViewDidFinishLoad(_ webView: UIWebView) {
loginIndicator.isHidden = true
loginIndicator.stopAnimating()
}
func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
webViewDidFinishLoad(webView)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}

Where to go from here

In this article you learned how to make UNSIGNED login request to Instagram using Swift3 in iOS app development. Download the source code from here  InstagramLogin-Swift.zip

If you have any questions then please feel free to comment. Thanks for reading. 

Comments

Popular Posts

How to recover data of your Android KeyStore?

These methods can save you by recovering Key Alias and Key Password and KeyStore Password. This dialog becomes trouble to you? You should always keep the keystore file safe as you will not be able to update your previously uploaded APKs on PlayStore. It always need same keystore file for every version releases. But it’s even worse when you have KeyStore file and you forget any credentials shown in above box. But Good thing is you can recover them with certain tricks [Yes, there are always ways]. So let’s get straight to those ways. 1. Check your log files → For  windows  users, Go to windows file explorer C://Users/your PC name/.AndroidStudio1.4 ( your android studio version )\system\log\idea.log.1 ( or any old log number ) Open your log file in Notepad++ or Any text editor, and search for: android.injected.signing and if you are lucky enough then you will start seeing these. Pandroid.injected.signing.store.file = This is  file path where t...

React Native - Text Input

In this chapter, we will show you how to work with  TextInput  elements in React Native. The Home component will import and render inputs. App.js import React from 'react' ; import Inputs from './inputs.js' const App = () => { return ( < Inputs /> ) } export default App Inputs We will define the initial state. After defining the initial state, we will create the  handleEmail  and the  handlePassword  functions. These functions are used for updating state. The  login()  function will just alert the current value of the state. We will also add some other properties to text inputs to disable auto capitalisation, remove the bottom border on Android devices and set a placeholder. inputs.js import React , { Component } from 'react' import { View , Text , TouchableOpacity , TextInput , StyleSheet } from 'react-native' class Inputs extends Component { state = { ...

How I Reduced the Size of My React Native App by 85%

How and Why You Should Do It I borrowed 25$ from my friend to start a Play Store Developer account to put up my first app. I had already created the app, created the assets and published it in the store. Nobody wants to download a todo list app that costs 25mb of bandwidth and another 25 MB of storage space. So today I am going to share with you how I reduced the size of Tet from 25 MB to around 3.5 MB. Size Matters Like any beginner, I wrote my app using Expo, the awesome React Native platform that makes creating native apps a breeze. There is no native setup, you write javascript and Expo builds the binaries for you. I love everything about Expo except the size of the binaries. Each binary weighs around 25 MB regardless of your app. So the first thing I did was to migrate my existing Expo app to React Native. Migrating to React Native react-native init  a new project with the same name Copy the  source  files over from Expo project Install all de...