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

What are the Alternatives of device UDID in iOS? - iOS7 / iOS 6 / iOS 5 – Get Device Unique Identifier UDID

Get Device Unique Identifier UDID Following code will help you to get the unique-device-identifier known as UDID. No matter what iOS user is using, you can get the UDID of the current iOS device by following code. - ( NSString *)UDID { NSString *uuidString = nil ; // get os version NSUInteger currentOSVersion = [[[[[UIDevice currentDevice ] systemVersion ] componentsSeparatedByString: @" . " ] objectAtIndex: 0 ] integerValue ]; if (currentOSVersion <= 5 ) { if ([[ NSUserDefaults standardUserDefaults ] valueForKey: @" udid " ]) { uuidString = [[ NSUserDefaults standardDefaults ] valueForKey: @" udid " ]; } else { CFUUIDRef uuidRef = CFUUIDCreate ( kCFAllocatorDefault ); uuidString = ( NSString *) CFBridgingRelease ( CFUUIDCreateString ( NULL ,uuidRef)); CFRelease (uuidRef); [[ NSUserDefaults standardUserDefaults ] setObject: uuidString ForKey: @" udid " ]; [[ NSUserDefaults standardUserDefaults ] synchro...

16 AWS Gotchas

16 AWS Gotchas In January I launched the MVP for my own startup,  Proximistyle , which helps you find what you’re looking for nearby. On advice from friends and industry contacts I chose AWS as my cloud provider. Having never had to set up my own cloud infrastructure before, the learning curve to get from no experience to a stable VPC system I was happy with was significantly steeper than expected, and had its fair share of surprises. #1 Take advantage of the free resources offered AWS offers a free tier for new accounts. If you have recently bought a domain and set up a company you qualify for the free tier for a year. Additionally, if you are a bootstrapped startup you can apply for  the Startup Builders package  and get $1000 in AWS credits. After doing the above, you’re now ready to get started with setting up the AWS infrastructure for your startup. #2 Set up billing budgets and alerting The very first thing you should do after setting up billing, is enabling a budge...

Ultimate Folder Structure For Your React Native Project

  Ultimate Folder Structure For Your React Native Project React native project structure React Native is a flexible framework, giving developers the freedom to choose their code structure. However, this can be a double-edged sword for beginners. Though it offers ease of coding, it can soon become challenging to manage as your project expands. Thus, a structured folder system can be beneficial in many ways like better organization, simplified module management, adhering to coding practices, and giving a professional touch to your project. This write-up discusses a version of a folder arrangement that I employ in my React Native projects. This structure is based on best practices and can be modified to suit the specific needs of your project. Before we get into the project structure let’s give credit to @sanjay who has the original idea of the structure but I modify his version of the code, to make it better. Base library axios  — For network calling. react-navigation ...