Integrate LinkedIn with Mobile Apps: Technical Guide

Integrate LinkedIn with Mobile Apps: Technical Guide

LinkedIn is among the most popular social networking platforms available today. The users of LinkedIn can share status updates, they can participate in group discussion on topics of their interest, read latest updates from their contacts and companies. With gaining popularity of social networking platforms like Facebook, LinkedIn and Twitter, the mobile app developers have indulged themselves in tightly integrating these services within their applications. This will allow users to share the content on networking sites without actually leaving the applications. Or something more simple and fun.
Let’s see the implementation of LinkedIn integration on both the platforms iOS and Android.

A – Android SDK For LinkedIn

A1: Get the Mobile SDK for Android

To start with, you first need to download the latest version of LinkedIn’s Mobile SDK for Android.

A2: Get the LinkedIn APK

To support the Mobile SDK of Android, users require the official LinkedIn Android application.
Note: For smoother development and debugging experience, you will require LinkedIn APK file and get them manually installed on virtual devices.

A3: Development Environment Set Up:

A3.1: First download and install IDE:

Many popular IDE choices are available for Android Development like Eclipse with the Android Developer Tools plugin, Google’s Android Studio and JetBrains IntelliJ IDEA

A3.2: Installation of Android SDK dependencies:

If you are working on a sample application you require to have Android SDK and have build-tools installed in your environment.

A4: Developing Sample Application:

Let’s follow the below mentioned instructions in detailing out the building LinkedIn Mobile SDK.

  • First launch Android Studio and select “Import Non-Android Studio project
  • Now select the build.gradle file in the root of Mobile SDK for Android archive
  • From navigation menu, select Build -> Make Project

Note: To function properly, Mobile SDK-enabled applications require the official LinkedIn Android app to be installed on the device.
Note: For running the sample apps on connected physical apps, you can get the LinkedIn app from your app store.
Note: If your sample apps are there to run on emulated Android device, then you can use your emulated device browser and download the LinkedIn APK file.

A5: Associating LinkedIn App With Your Android App:

You can add some specific information about LinkedIn application into your Android Application by using LinkedIn Application settings.
If you have not created any application, you can create the same otherwise you can also modify the existing application by selecting modifying its settings.
The two types of key hashes are Debug (which is development) and Release (which is production).
1- Debug Keys: These keys are required for LinkedIn in order to verify the authenticity of application.
2- Release Keys: These keys are required as all the Android application must be signed with it before they get uploaded to PlayStore.

A5.1: Generating Debug key hash value

You can use the following below mentioned command in order to generate a debug key hash value. The location of key hash store will differ depending on whether the developer is developing on a Windows or Mac platform:
windows
keytool -exportcert -keystore %HOMEPATH%\.android\debug.keystore -alias androiddebugkey | openssl sha1 -binary | openssl base64
mac/unix
keytool -exportcert -keystore ~/.android/debug.keystore -alias androiddebugkey | openssl sha1 -binary | openssl base64

A5.2: Generating a release key hash value:

You can use below command for generating release key hash value:
keytool -exportcert -keystore YOUR_RELEASE_KEY_PATH -alias YOUR_RELEASE_KEY_ALIAS | openssl sha1 -binary | openssl base64

A5.3: Configure the values

Provide one or more values with comma-separation format in the “Package Name and Package Hash” under the head of “Android Settings”.
Android.Package.Name,Key-Hash-Value

A5.4: Authenticating mobile users:

Before using the actual functionality of mobile SDK, you must create an authenticated LinkedIn session. Let’s have a look of how to authenticate LinkedIn users in the Android environment:
Authentication:
Before you start, you need to first register your application with LinkedIn and get the API keys. You must also ensure that you must know all the relevant information which is necessary to authenticate a LinkedIn user within your mobile application.

A5.4.1: Initialization- let’s see how to maintain a initialization connection to LinkedIn

LISessionManager is an important element of Mobile SDK for Android which provides all the necessary functionality regarding creation and managing of LISession object. You must know that there are two ways of initializing a LinkedIn session by using the overloaded init() method:

  • Without an existing access token
  • With a previously acquired access token
A5.4.1.1: Initialization by requesting a new access token

For new access token the init() will communicate with the official LinkedIn mobile application and will request new token for the current user. Doing this the user is taken out from application’s flow and gets directed into the official LinkedIn Android Application which results into several possible user experiences.
Let’s see how the initialization part of authentication process might look like:

java
public class MainActivity extends Activity
 {

   @Override
   protected void onCreate(Bundle savedInstanceState) {    
       // Store a reference to the current activity
       final Activity thisActivity = this;

       LISessionManager.getInstance(getApplicationContext()).init(thisActivity, buildScope(), new AuthListener() {
           @Override
           public void onAuthSuccess() {
               // Authentication was successful.  You can now do
               // other calls with the SDK.
           }

           @Override
           public void onAuthError(LIAuthError error) {
               // Handle authentication errors
           }
       }, true);
   }
}

// Build the list of member permissions our LinkedIn session requires
private static Scope buildScope() {
   return Scope.build(Scope.R_BASICPROFILE, Scope.W_SHARE);
}
A5.4.1.2: Initialization with an existing access token:

You may also have token for the current user for which you have serialized from a previous interaction with your application. You can use it to create a new LISession object instead of requesting a brand new one.

java
LISessionManager.getInstance(getApplicationContext()).init(AccessToken accessToken);

Note: It should be noted that access tokens which are acquired via the Mobile SDK can only be used with Mobile SDK and can’t be used to make server side REST API calls.

A5.4.2: Handle responses from the LinkedIn mobile app

Making requests to the official LinkedIn app also validates that your app also need to handle the resulting responses which can be done by calling LISessionManager’s implementation ofonActivityResult() from within the calling activity’s onActivityResult() method.

java
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
   // Add this line to your existing onActivityResult() method
   LISessionManager.getInstance(getApplicationContext()).onActivityResult(this, requestCode, resultCode, data);
}

As soon as you application starts sending and receiving messages from the LinkedIn Mobile App successfully, your authentication workflow gets completed soon.

A5.5: Authenticated REST API calls:

Once you get all your users authenticated, you can easily make calls to LinkedIn’s REST API:

A5.5.1: APIHelper.getRequest()
java
String url = "https://api.linkedin.com/v1/people/~:(id,first-name,last-name)";
               
APIHelper apiHelper = APIHelper.getInstance(getApplicationContext());
apiHelper.getRequest(this, url, new ApiListener() {
   @Override
   public void onApiSuccess(ApiResponse apiResponse) {
       // Success!
   }

   @Override
   public void onApiError(LIApiError liApiError) {
       // Error making GET request!
   }
});
A5.5.2: APIHelper.postRequest()
java
String url = "https://api.linkedin.com/v1/people/~/shares";

JSONObject body = new JSONObject("{" +
   "\"comment\": \"Sample share\"," +
   "\"visibility\": { \"code\": \"anyone\" }," +
   "\"content\": { " +
       "\"title\": \"Sample share\"," +
       "\"description\": \"Testing the mobile SDK call wrapper!\"," +
       "\"submitted-url\": \"http://www.example.com/\"," +
       "\"submitted-image-url\": \"http://www.example.com/pic.jpg\"" +
   "}" +
"}");
              
APIHelper apiHelper = APIHelper.getInstance(getApplicationContext());
apiHelper.postRequest(this, url, body, new ApiListener() {
   @Override
   public void onApiSuccess(ApiResponse apiResponse) {
       // Success!
   }

   @Override
   public void onApiError(LIApiError liApiError) {
       // Error making POST request!
   }
});
A5.5.3: APIHelper.putRequest()
java
String url = "https://api.linkedin.com/v1/companies/1234/updates/key=ABCDE-123456/update-comments-as-company/";

JSONObject body = new JSONObject("{" +
   "\"comment\": \"Sample share\" +
"}");
              
APIHelper apiHelper = APIHelper.getInstance(getApplicationContext());
apiHelper.putRequest(this, url, body, new ApiListener() {
   @Override
   public void onApiSuccess(ApiResponse apiResponse) {
       // Success!
   }

   @Override
   public void onApiError(LIApiError liApiError) {
       // Error making POST request!
   }
});

A5.6: Cancelling in-progress requests

You may also wish to cancel any in-progress API requests which can be done be calling APIHelper.cancelCalls() method.

java
APIHelper apiHelper = APIHelper.getInstance(getApplicationContext());
apiHelper.cancelCalls(this);

B – iOS SDK For LinkedIn

Mobile SDK for iOS allows you to decrease your application’s time to market by providing support for LinkedIn natively inside iOS application. Henceforth,

B1: Setting up your development environment

B1.1: Get the latest Xcode

You have to ensure that you are running Xcode version 6.1.1 or greater.

B1.2: Download the SDK

To start with LinkedIn integration in iOS application you first have to download the latest release of the LinkedIn Mobile SDK for iOS.

B2: Building the Sample Applications

You can use following instructions for building LinkedIn Mobile SDK:
1- First, download and open the latest version of the LinkedIn Mobile SDK for iOS.
2- Second, open either the eventsApp or SampleApp folder.
3- Therefore, now do double-click on either the eventsapp.xcodeproj or SampleApp.xcodeproj file.
4- And, now select Product -> Run from the top navigation.

B3: Associate LinkedIn App with your iOS apps:

If by now you have not created an application, you first have to create an application. If you already have an existing LinkedIn application, you can get it configured on developer’s website. You can also do the same by using ‘Mobile’ setting page and then configure application’s Bundle ID value to your LinkedIn application settings. You can easily find your bundle ID in the ‘General Properties’ of your Xcode project:

B3.1: Configuring Bundle ID:

You can easily associate your iOS application with your LinkedIn application by using your Bundle ID value or values.

B3.2: Determining LinkedIn App ID value

You need to first know your LinkedIn application’s “Application ID” before making necessary changes to your Info.plist file,

B3.3: Configure your application’s info.plist

You first have to locate the Supporting Files -> Info.plist file in your Xcode project and then add the values.

info.plist
<key>LIAppId</key>
<string>{Your LinkedIn app ID}</string>

<key>CFBundleURLTypes</key>
<array>
        	<dict>
                    	<key>CFBundleURLSchemes</key>
                    	<array>
                                	<string>li{Your LinkedIn app ID}</string>
                    	</array>
        	</dict>
</array>

B3.4: iOS 9 Compatibility

While if you are targeting iOS 9 support in your application, you just have to follow some additional steps to run successfully the build and run your app:

B3.4.1: Whitelisting LinkedIn Custom Schemes

Add the following configuration to your application’s Info.plist file:

info.plist
<key>LSApplicationQueriesSchemes</key>
<array>
   <string>linkedin</string>
   <string>linkedin-sdk2</string>
   <string>linkedin-sdk</string>
</array>
B3.4.2: Bitcode Support

In Xcode, click on your application target and under Build Settings -> Build Options, setEnable Bitcode to No.
This is required because it will be in disabled position in case of iOS 9 compilation process.

B3.4.3: App Transport Security

In iOS 9, Apple enforces the use of secure HTTPS connections between an app and server. If your application makes calls over HTTPS, there will be no compatibility issues. But, if your application make requests to insecure HTTP, it is required to specify the insecure domain in your app’s Info.plist file.

info.plist
<key>NSAppTransportSecurity</key>
<dict>
   <key>NSExceptionDomains</key>
   <dict>
       <key>linkedin.com</key>
       <dict>
           <key>NSExceptionAllowsInsecureHTTPLoads</key>
           <true/>
           <key>NSIncludesSubdomains</key>
           <true/>                
           <key>NSExceptionRequiresForwardSecrecy</key>
           <false/>
       </dict>
   </dict>
</dict>

B3.5: Using the SDK

Following are the basic steps for using iOS SDK:

  • Authenticating LinkedIn members
  • Making authenticated API calls
  • Deep linking to additional member content
B3.5.1: Importing the SDK

For importing you have to open the Mobile SDK for iOS archive and then drag linkedin-sdk.framework into the Xcode Project Navigator pane. For smoother development experience, it is recommended that include the following header in your code:

objective-c
#import <linkedin-sdk/LISDK.h>
B3.5.2: Handling responses from LinkedIn mobile app

Wherever you are brought outside the context of your application you can add the following method to your AppDelegate.m source code. This enables the LinkedIn App to give control back to your application.

objective-c
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
   if ([LISDKCallbackHandler shouldHandleUrl:url]) {
       return [LISDKCallbackHandler application:application openURL:url sourceApplication:sourceApplication annotation:annotation];
   }
   return YES;
}
B3.5.3: Making Authenticated REST API calls

You can easily make call to LinkedIn’s REST API once your users are authenticated and they have authorization for your application.

B3.5.3.1: getRequest
objective-c
[[LISDKAPIHelper sharedInstance] getRequest:(NSString *)url
          success:(void(^)(LISDKAPIResponse *))success
            error:(void(^)(LISDKAPIError *))error]
B3.5.3.2: postRequest
objective-c
[[LISDKAPIHelper sharedInstance] postRequest:(NSString *)url
              body:(NSData *)body
           success:(void(^)(LISDKAPIResponse *))successCompletion
             error:(void(^)(LISDKAPIError *))errorCompletion]
objective-c
[[LISDKAPIHelper sharedInstance] postRequest:(NSString *)url
        stringBody:(NSString *)stringBody
           success:(void(^)(LISDKAPIResponse *))successCompletion
             error:(void(^)(LISDKAPIError *))errorCompletion]
B3.5.4: in-progress requests cancellation

You may want to cancel any in-progress API requests. This can be done by calling the cancelCalls method.

C- Conclusion:

This can be of great help for developers who are looking for LinkedIn integration on their mobile apps. Feel free to drop your comment.

References: 3 Pillar Global, Telegraph, Stack Overflow, Innofied, Linkedin Developers Docs

The following two tabs change content below.
Rachit Agarwal

Rachit Agarwal

Director and Co-Founder at Algoworks Technologies
Rachit is leading the mobility business development function, mobility strategy and consulting practice at Algoworks. He is an expert of all mobile technologies and has experience in managing teams involved in the development of custom iPhone/iPad/Android apps.
Rachit Agarwal

Latest posts by Rachit Agarwal (see all)

Rachit AgarwalIntegrate LinkedIn with Mobile Apps: Technical Guide