Skip to main content

How to Integrate Instagram Login in IOS - Objective C

Introduction to Instagram integration in iOS



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

Instagram is a popular social network and most IOS developers integrate Instagram API in their apps. In this post we will look at the steps of integrating and authenticating user's (both signed authentication or unsigned authentication) with Instagram in IOS.

Note: For swift3 tutorial on Instagram login, please visit Integrate Instagram login using Swift3 Tutorial

Register app with Instagram

First register your app with Instagram and get CLIENT ID and CLIENT SECRET. To register your app with Instagram click below link

http://instagram.com/developer/

Log in to the portal and click Manage Client

Register app on Instagram
Manage Clients
Click Register New Client, and register your app by filling necessary fields as mentioned below

1. Application Name
2. Description about application
3. Website
4. OAUTH redirect uri : Required if user denied access to your application then Instagram will redirect user to this uri filled by you in this field. You can enter same URL as entered in website field.

Next you have to select authentication options

1. Disable implicit OAuth : By enabling or checking this option you are telling that your app use Signed authentication that use server side OAUTH flow. If you want client side authentication that is unsigned calls then you can do it by unchecking the checkbox.

2. Enforce signed header:  This option provide your app with better security as access token can be stolen and  reused elsewhere. 

To make a signed request you have to tick mark both checkboxes and if you want unsigned request then you can keep both of these checkboxes unchecked. Click register to create an application on Instagram.

Jump to code

Now at this point you have your client id  and client secret with you.


Code in ViewController.h file

Open your viewController.h file and create IBOutlet for  UIWebView, UIActivityIndicatorView,
UILabel. We need property to differentiate weather we are going to use unsigned authentication or signed authentication.


@interface LoginViewController : UIViewController<UIWebViewDelegate>
{


    IBOutlet UIWebView *loginWebView;
    IBOutlet UIActivityIndicatorView* loginIndicator;
    IBOutlet UILabel *loadingLabel;
}
@property(strong,nonatomic)NSString *typeOfAuthentication;

@end

Designing Interface

Open .xib, drag all controls declared in viewController.h file and connect outlets with them. Set UIWebView delegates as we need to implement delegates.

Code in ViewController.m file


TypeOfAuthentication is to be set when you are navigating to viewController or you can set it in viewDidLoad method as

self.typeOfAuthentication = @"UNSIGNED"

Open your viewController.m file and in its viewDidAppear method load your loginWebView with authorisation url, 


- (void) viewDidAppear:(BOOL)animated
{
    [super viewDidAppear: animated];
    
    [[UIApplication sharedApplication] setStatusBarHidden:YES];
    
    NSString* authURL = nil;
    
    if ([typeOfAuthentication isEqualToString:@"UNSIGNED"])
    {
         authURL = [NSString stringWithFormat: @"%@?client_id=%@&redirect_uri=%@&response_type=token&scope=%@&DEBUG=True",
         INSTAGRAM_AUTHURL,
         INSTAGRAM_CLIENT_ID,
         INSTAGRAM_REDIRECT_URI,
         INSTAGRAM_SCOPE];

    }
    else
    {
         authURL = [NSString stringWithFormat: @"%@?client_id=%@&redirect_uri=%@&response_type=code&scope=%@&DEBUG=True",
                             INSTAGRAM_AUTHURL,
                             INSTAGRAM_CLIENT_ID,
                             INSTAGRAM_REDIRECT_URI,
                             INSTAGRAM_SCOPE];
    }
    
    
    [loginWebView loadRequest: [NSURLRequest requestWithURL: [NSURL URLWithString: authURL]]];
    [loginWebView setDelegate:self];
}

Constants used

#define INSTAGRAM_AUTHURL                               @"https://api.instagram.com/oauth/authorize/"
#define INSTAGRAM_APIURl                                @"https://api.instagram.com/v1/users/"
#define INSTAGRAM_CLIENT_ID                             @"your client id"
#define INSTAGRAM_CLIENTSERCRET                         @"your client secret"
#define INSTAGRAM_REDIRECT_URI                          @"http://www.iostutorialjunction.com"
#define INSTAGRAM_ACCESS_TOKEN                          @"access_token"
#define INSTAGRAM_SCOPE                                 @"likes+comments+relationships"

Below are the UIWebView delegate methods that we need to implement. 

shouldStartLoadRequest : This is needed as we need to cross check our authentication with Instagram and here we get our access Token (in case of unsigned call ) and code (in case of signed call)

webViewDidStartLoad: To show activity indicator animated

webViewFinishLoad: To hide activity indicator.

failWithError: In case we are not able to load webView then stop activity indicator.  


- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request
 navigationType:(UIWebViewNavigationType)navigationType
{


    return [self checkRequestForCallbackURL: request];
}

- (void) webViewDidStartLoad:(UIWebView *)webView
{
    [loginIndicator startAnimating];
    loadingLabel.hidden = NO;
    [loginWebView.layer removeAllAnimations];
    loginWebView.userInteractionEnabled = NO;
    [UIView animateWithDuration: 0.1 animations:^{
      //  loginWebView.alpha = 0.2;
    }];
}

- (void) webViewDidFinishLoad:(UIWebView *)webView
{
    [loginIndicator stopAnimating];
    loadingLabel.hidden = YES;
    [loginWebView.layer removeAllAnimations];
    loginWebView.userInteractionEnabled = YES;
    [UIView animateWithDuration: 0.1 animations:^{
        //loginWebView.alpha = 1.0;
    }];
}

- (void) webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    [self webViewDidFinishLoad: webView];
}


In shouldStartLoadRequest method we will check for callBackUrl we get from Instagram. Below is the implementation code for callback url check. Here if we get our redirect url that we gave while creating client on Instagram in the callback url request then, we will fetch token in our handleAuth method(in case of unsigned call) or we will extract code from url and make a post request to Instagram server(in case of signed call)

- (BOOL) checkRequestForCallbackURL: (NSURLRequest*) request
{
    NSString* urlString = [[request URL] absoluteString];
    
    if ([typeOfAuthentication isEqualToString:@"UNSIGNED"])
    {
        // check, if auth was succesfull (check for redirect URL)
          if([urlString hasPrefix: INSTAGRAM_REDIRECT_URI])
         {
             // extract and handle access token
             NSRange range = [urlString rangeOfString: @"#access_token="];
             [self handleAuth: [urlString substringFromIndex: range.location+range.length]];
             return NO;
         }
    }
    else
    {
        if([urlString hasPrefix: INSTAGRAM_REDIRECT_URI])
        {
            // extract and handle code
            NSRange range = [urlString rangeOfString: @"code="];
            [self makePostRequest:[urlString substringFromIndex: range.location+range.length]];
            return NO;
        }
    }
    
    return YES;

}



Below is the code for  both makePostRequest and handleAuth methods

-(void)makePostRequest:(NSString *)code
{
    
    NSString *post = [NSStringstringWithFormat:@"client_id=%@&client_secret=%@&grant_type=authorization_code&redirect_uri=%@&code=%@",INSTAGRAM_CLIENT_ID,INSTAGRAM_CLIENTSERCRET,INSTAGRAM_REDIRECT_URI,code];
    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];
    
    NSMutableURLRequest *requestData = [NSMutableURLRequest requestWithURL:
                                        [NSURL URLWithString:@"https://api.instagram.com/oauth/access_token"]];
    [requestData setHTTPMethod:@"POST"];
    [requestData setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [requestData setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [requestData setHTTPBody:postData];
    
    NSURLResponse *response = NULL;
    NSError *requestError = NULL;
    NSData *responseData = [NSURLConnection sendSynchronousRequest:requestData returningResponse:&response error:&requestError];
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragmentserror:nil];
    [self handleAuth:[dict valueForKey:@"access_token"]];
    
}

- (void) handleAuth: (NSString*) authToken
{
    NSLog(@"successfully logged in with Tocken == %@",authToken);
  
}

 If everything goes fine then you will get your auth token. In handleAuth you can dismiss the controller so that it take you back to your application and store the token in user defaults.

Now you can make request to Instagram server. If error persists then track back above steps.


Comments

Popular Posts

Master Map & Filter, Javascript’s Most Powerful Array Functions

Master Map & Filter, Javascript’s Most Powerful Array Functions Learn how Array.map and Array.filter work by writing them yourself This article is for those who have written a  for  loop before, but don’t quite understand how  Array.map  or  Array.filter  work. You should also be able to write a basic function. By the end of this, you’ll have a complete understanding of both functions, because you’ll have seen how they’re written. Array.map Array.map  is meant to transform one array into another by performing some operation on each of its values. The original array is left untouched and the function returns a new, transformed array. For example, say we have an array of numbers and we want to  multiply each number by three . We also don’t want to change the original array. To do this without  Array.map , we can use a standard for-loop. for-loop var originalArr = [1, 2, 3, 4, 5]; var newArr = []; for(var i = 0; i < originalArr.length; i+...

Integrate the FaceID or TouchID Authentication in iOS Apps - Swift

FaceID or TouchID Authentication Dear Folks, today I am going to explain the proper way to integrate the Face ID or Touch ID in iOS App. Face ID and Touch ID are secure, familiar authentication methods that people trust. Follow below steps: Step 1: Add NSFaceIDUsageDescription Key in info.plist file <key>NSFaceIDUsageDescription</key> <string>This app requires Face ID permission to authenticate using Face recognition.</string> Step 2: Create a swift file with any name but it would be better to related to its functionality, Like BioMetrixFile.swift Step 3: In BioMetrixFile write below codes and follow instructions. But before proceeding further import LocalAuthentication class in BioMetrixFile. Now, create typealias for success or failure blocks to well manage Authentication Success or Failure. public typealias AuthenticationSuccess = (() -> ()) public typealias AuthenticationFailure = ((AuthenticationError) -> ()) Now written all s...

React Native: How To Open App Settings Page

  React Native: How To Open App Settings Page React Native has a Linking module to manage the interaction with other applications in the device. In this article, I will explain how you can open “Application Setting Page” of the device using. Sample Case Before I explain how to do this, I’ll talk about an example case where we might need this: You need to get location permission within the application from a user using an iOS operating system and you asked for permission. But user did not agree to grant this permission the first time. In this case, you cannot ask your user for location permission the second time. In this case, the only thing to do is to direct the user to the settings page of our application and make it manually allow it. Now that we have explained our example situation, we can move on to how we can redirect our user to the “settings page of our application”. Open App Settings Page iOS If our user is using an iOS operating system, we can handle the whole process wit...