Linkedin Integration in Native iOS

Posted By : Ashish Tyagi | 29-Nov-2013

Integration of Linkedin Api in IOS

The LinkedIn platform provides you the ability to register and sign-in to your application or website with their LinkedIn identity and also allow user to connect their LinkedIn account to your application, in order to easily publish their activities to their linkedIn account.

Get started to Integrate Linkedin Api in iOS App :

1.) Create a Project in your xcode using “Empty Application” in your Xcode and note their bundle id which will be needed when you register your app on Linkedin Website.

2.) Create a UIViewController class with their xib ( like LoginLinkedInViewController ) and set it as a rootViewController of Window in AppDelegate class.

3.) First of all,you have to register your app here https://www.linkedin.com/secure/developer by using your current linked account or create a new one linkedin account.

4.) After completion of registation of your app on Linkedin website, you will get a API Key,Secret Key ,OAuth User Token and OAuth User Secret.

Here ,we are a using a Library OAutho for integrating with user linkedin account and after login User can post a status to their linkedin account.

5.) First of all ,you have to download Library from here and unzip it. Now you have to drag and drop OAuthLoginView,ASIHTTP and OAuthStarterKit folder in Project Navigator of Xcode.

6.) For Removing Linking error in xcode ,you have to add -all_load,-ObjC and -lc++ flag as shown bellow.

7.) Expand “Link Binaries with Libraries”. Select the “+” button, and add these frameworks SystemConfiguration.framework ,CFNetwork.framework and libz.dylib.

8.) Open your ViewController.h file and make some change like given below.


#import <UIKit/UIKit.h>
#import "OAuthLoginView.h"
#import "JSONKit.h"
#import "OAConsumer.h"
#import "OAMutableURLRequest.h"
#import "OADataFetcher.h"
#import "OATokenManager.h"


@interface LoginLinkedInViewController : UIViewController
{
    
}

@property (nonatomic, strong) IBOutlet UIButton *buttonLogin;
@property (nonatomic, strong) IBOutlet UIButton *buttonPost;
@property (nonatomic, strong) IBOutlet UIButton *buttonLogout;

@property (nonatomic, strong) IBOutlet UILabel *userName;
@property (nonatomic, strong) IBOutlet UILabel *headline;
@property (nonatomic, strong) IBOutlet UILabel *status;
@property (nonatomic, strong) IBOutlet UILabel *updateStatusLabel;
@property (nonatomic, strong) IBOutlet UITextField *statusTextView;
@property (strong, nonatomic) IBOutlet UILabel *linkedinProfileLabel;


@property (nonatomic, strong) OAuthLoginView *oAuthLoginView;


- (IBAction)buttonLoginClick:(UIButton *)sender;
- (IBAction)buttonPostStatusClick:(UIButton *)sender;
- (IBAction)buttonLogoutClick:(id)sender;

- (void)profileApiCall;
- (void)networkApiCall;

9.) Again open your ViewController.m file and make some change like given below.

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma Marks - Public Methods ::


- (IBAction)buttonLoginClick:(UIButton *)sender
{
    self.oAuthLoginView = [[OAuthLoginView alloc] initWithNibName:nil bundle:nil];
    
    // register to be told when the login is finished
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(loginViewDidFinish:)
                                                 name:@"loginViewDidFinish"
                                               object:self.oAuthLoginView];
    
    [self presentViewController:self.oAuthLoginView animated:YES completion:nil];
}

-(void) loginViewDidFinish:(NSNotification*)notification
{
	[[NSNotificationCenter defaultCenter] removeObserver:self];
    
    // We're going to do these calls serially just for easy code reading.
    // They can be done asynchronously
    // Get the profile, then the network updates
    [self profileApiCall];
	
}


- (void)profileApiCall
{
    NSURL *url = [NSURL URLWithString:@"http://api.linkedin.com/v1/people/~"];
    OAMutableURLRequest *request =
    [[OAMutableURLRequest alloc] initWithURL:url
                                    consumer:self.oAuthLoginView.consumer
                                       token:self.oAuthLoginView.accessToken
                                    callback:nil
                           signatureProvider:nil];
    
    [request setValue:@"json" forHTTPHeaderField:@"x-li-format"];
    
    OADataFetcher *fetcher = [[OADataFetcher alloc] init];
    [fetcher fetchDataWithRequest:request
                         delegate:self
                didFinishSelector:@selector(profileApiCallResult:didFinish:)
                  didFailSelector:@selector(profileApiCallResult:didFail:)];
    
}



- (void)profileApiCallResult:(OAServiceTicket *)ticket didFinish:(NSData *)data
{
    NSString *responseBody = [[NSString alloc] initWithData:data
                                                   encoding:NSUTF8StringEncoding];
    
    NSDictionary *profile = [responseBody objectFromJSONString];
    
    if ( profile )
    {
        
        [self.buttonLogin setHidden:YES];
        
        self.userName.text = [[NSString alloc] initWithFormat:@"%@ %@",
                     [profile objectForKey:@"firstName"], [profile objectForKey:@"lastName"]];
        
        self.headline.text = [profile objectForKey:@"headline"];
    }
    
    // The next thing we want to do is call the network updates
    [self networkApiCall];
    
}

- (void)profileApiCallResult:(OAServiceTicket *)ticket didFail:(NSData *)error
{
    NSLog(@"%@",[error description]);
}

- (void)networkApiCall
{
    NSURL *url = [NSURL URLWithString:@"http://api.linkedin.com/v1/people/~/network/updates?scope=self&count=1&type=STAT"];
    OAMutableURLRequest *request =
    [[OAMutableURLRequest alloc] initWithURL:url
                                    consumer:self.oAuthLoginView.consumer
                                       token:self.oAuthLoginView.accessToken
                                    callback:nil
                           signatureProvider:nil];
    
    [request setValue:@"json" forHTTPHeaderField:@"x-li-format"];
    
    OADataFetcher *fetcher = [[OADataFetcher alloc] init];
    [fetcher fetchDataWithRequest:request
                         delegate:self
                didFinishSelector:@selector(networkApiCallResult:didFinish:)
                  didFailSelector:@selector(networkApiCallResult:didFail:)];
    
}

- (void)networkApiCallResult:(OAServiceTicket *)ticket didFinish:(NSData *)data
{
    NSString *responseBody = [[NSString alloc] initWithData:data
                                                   encoding:NSUTF8StringEncoding];
    
    NSDictionary *person = [[[[[responseBody objectFromJSONString]
                               objectForKey:@"values"]
                              objectAtIndex:0]
                             objectForKey:@"updateContent"]
                            objectForKey:@"person"];
    
    
    if ( [person objectForKey:@"currentStatus"] )
    {
        [self.buttonPost setHidden:false];
        [self.buttonLogout setHidden:false];
        [self.statusTextView setHidden:false];
        [self.updateStatusLabel setHidden:false];
        self.status.text = [person objectForKey:@"currentStatus"];
    }
    else
    {
        [self.buttonPost setHidden:false];
        [self.buttonLogout setHidden:false];
        [self.statusTextView setHidden:false];
        [self.updateStatusLabel setHidden:false];
        self.status.text = [[[[person objectForKey:@"personActivities"]
                         objectForKey:@"values"]
                        objectAtIndex:0]
                       objectForKey:@"body"];
        
    }
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)networkApiCallResult:(OAServiceTicket *)ticket didFail:(NSData *)error
{
    NSLog(@"%@",[error description]);
}



- (IBAction)buttonPostStatusClick:(UIButton *)sender
{
    [self.statusTextView resignFirstResponder];
    NSURL *url = [NSURL URLWithString:@"http://api.linkedin.com/v1/people/~/shares"];
    OAMutableURLRequest *request =
    [[OAMutableURLRequest alloc] initWithURL:url
                                    consumer:self.oAuthLoginView.consumer
                                       token:self.oAuthLoginView.accessToken
                                    callback:nil
                           signatureProvider:nil];
    
    NSDictionary *update = [[NSDictionary alloc] initWithObjectsAndKeys:
                            [[NSDictionary alloc]
                             initWithObjectsAndKeys:
                             @"anyone",@"code",nil], @"visibility",
                            self.statusTextView.text, @"comment", nil];
    
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    NSString *updateString = [update JSONString];
    
    [request setHTTPBodyWithString:updateString];
	[request setHTTPMethod:@"POST"];
    
    OADataFetcher *fetcher = [[OADataFetcher alloc] init];
    [fetcher fetchDataWithRequest:request
                         delegate:self
                didFinishSelector:@selector(postUpdateApiCallResult:didFinish:)
                  didFailSelector:@selector(postUpdateApiCallResult:didFail:)];
   
}

- (void)postUpdateApiCallResult:(OAServiceTicket *)ticket didFinish:(NSData *)data
{
    // The next thing we want to do is call the network updates
    [self networkApiCall];
    
}

- (void)postUpdateApiCallResult:(OAServiceTicket *)ticket didFail:(NSData *)error
{
    NSLog(@"%@",[error description]);
}

- (IBAction)buttonLogoutClick:(id)sender
{
    
    [self.buttonLogin setHidden:NO];
    
    NSString *tokenKey = @"";
    
    [[NSUserDefaults standardUserDefaults] setObject:tokenKey forKey:@"TokenKey"];
    
    
    [self.navigationController popViewControllerAnimated:YES];
    UIAlertView *logoutMessageAlert =[[UIAlertView alloc]initWithTitle:@"Alert" message:@"Logout Sucessfully !" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
    [logoutMessageAlert show];
    
}

   

10.) Now, You have to design your xib view like shown below and connect all IBOutlet for all field which are decelared in your ViewController.h file.

11.) On running your application, you will see your created view with linkedin login button. when you click on login button, then a new window is open which will see like shown below.

12. After login with your linkedin account, you will see Your Name ,Headline and Status in your app as shown in following image.

13.) At Last, You can also use given Sample code after changing API Key and Secret Key in initLinkedInApi method of Library/AutoLoginView/OAuthLoginView.m class.

Hope it is useful for you :)

Aashish Tyagi

[email protected]

About Author

Author Image
Ashish Tyagi

Ashish is a iPhone application developer with experience in Objective-C , Titanium and Phonegap frameworks. Ashish loves watching movies in his free time.

Request for Proposal

Name is required

Comment is required

Sending message..