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

Reloading UITableView while Animating Scroll in iOS 11

Reloading UITableView while Animating Scroll Calling  reloadData  on  UITableView  may not be the most efficient way to update your cells, but sometimes it’s easier to ensure the data you are storing is in sync with what your  UITableView  is showing. In iOS 10  reloadData  could be called at any time and it would not affect the scrolling UI of  UITableView . However, in iOS 11 calling  reloadData  while your  UITableView  is animating scrolling causes the  UITableView  to stop its scroll animation and not complete. We noticed this is only true for scroll animations triggered via one of the  UITableView  methods (such as  scrollToRow(at:at:animated:) ) and not for scroll animations caused by user interaction. This can be an issue when server responses trigger a  reloadData  call since they can happen at any moment, possibly when scroll animation is occurring. Example of s...

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...

Xcode & Instruments: Measuring Launch time, CPU Usage, Memory Leaks, Energy Impact and Frame Rate

When you’re developing applications for modern mobile devices, it’s vital that you consider the performance footprint that it has on older devices and in less than ideal network conditions. Fortunately Apple provides several powerful tools that enable Engineers to measure, investigate and understand the different performance characteristics of an application running on an iOS device. Recently I spent some time with these tools working to better understand the performance characteristics of an eCommerce application and finding ways that we can optimise the experience for our users. We realised that applications that are increasingly performance intensive, consume excessive amounts of memory, drain battery life and feel uncomfortably slow are less likely to retain users. With the release of iOS 12.0 it’s easier than ever for users to find applications that are consuming the most of their device’s finite amount of resources. Users can now make informed decisions abou...