Get A Quote
11Jul 2016

Integrating LinkedIn Sign In with iOS Application

2 Comments   IPhone
linkdin_blog

Let’s become proficient in how to integrate LinkedIn in your iOS application.

Note : This blog is about how to integrate LinkedIn Login in your iOS app with LinkedIn REST API. You also can integrate with LinkedIn Mobile SDK for that check below link. https://developer.linkedin.com/docs/signin-with-linkedin
Let’s start by creating New App in LinkedIn Developer.

Step : 1 Create New App in LinkedIn Developer.

  • Login to LinkedIn Developer (Here is the link https://developer.linkedin.com/)
  • Select MyApps -> Create Application
  • Fill all the details to create new application. All fields are mandatory.

 

2016-07-06_1816

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  • After filling all the detail click on submit button you will see below screen.

 

Screen Shot 2016-07-08 at 12.27.35 PM

 

  • You can find ClienID and ClientSecret from there. Also you can update application permissions and Authorized Redirect URLs.
  • r_basicprofile is by default checked, if you want to fetch email then also check r_emailaddress.
  • Then we have to provide Authorized Redirect URL inside OAuth 2.0 section. Its needed when user tries to refresh an existing access token. User does not require to login again if he has already login previously, the OAuth flow will automatically redirect the app using that URL. For normal login process that URL is exchanged between client App and the server while fetching Authorization code and access token.
  • The authorization URL should not real or existing URL. You can provide any value starting with “https://”.
  • Don’t forget to click update button after changing all information.

Step : 2 Create XCode project name it “LILoginDemo”.

Step : 3 Create UI For Application

  • In your viewController add labels for firstName, lastName, email, Id, public url, if you want to display other details then also add labels for them.
  • Add 2 buttons Login Using LinkedIn and Get Profile Details.
  • Add another view controller and add webview inside it.
  • Add a WebViewController.swift file assign it to another view controller in storyboard.
  • Give segue from Login Using LinkedIn button to other view controller.
  • Your Storyboard should look like below image.

 

Screen Shot 2016-07-07 at 4.12.28 PM

Step : 4 Prepare Request to get Authorization Code

1
2
3
4
let linkedInKey = "759w69ead3dlej"
let linkedInSecret = "7Fw3tWZTGEhAnKAY"
let authorizationEndPoint = "https://www.linkedin.com/uas/oauth2/authorization"
let accessTokenEndPoint = "https://www.linkedin.com/uas/oauth2/accessToken"
  • Our main goal in this step is to prepare the request for getting the authorization code, and to load it through a web view.
  • The request to get authorization code must require following parameters.
    • response_type: It’s a standard value that must always be: code
    • Client_id: It’s the Client ID value taken from the LinkedIn Developer’s website and been assigned to the linkedInKey
    • redirect_uri: The authorized redirection URL value that you have specified while creating application in LinkedIn Developer’s website.
    • state: A unique string required to prevent a cross-site request forgery (CSRF).
    • scope: A URL-encoded list of the permissions that our app requests.
  • Now create a method in WebViewController with name startAuthorization().
  • Inside this method specify request parameters as shown in below code snippet.
1
2
// Specify the response type which should always be "code".
let responseType = "code"

// Set the redirect URL which you have specify at time of creating application in LinkedIn Developer’s website. Adding the percent escape characthers is necessary.
let redirectURL = “https://com.test.linkedin/oauth”.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.alphanumericCharacterSet())!

// Create a random string based on the time interval (it will be in the form linkedin12345679).
let state = “linkedin\(Int(NSDate().timeIntervalSince1970))”

// Set preferred scope.
let scope = “r_basicprofile, r_emailaddress”

  • Next step is to compose the authorization URL. For that use URL assigned to authorizationEndPoint, and append all parameters.
1
2
3
4
5
6
7
8
// Create the authorization URL string.
var authorizationURL = "\(authorizationEndPoint)?"
authorizationURL += "response_type=\(responseType)&"
authorizationURL += "client_id=\(linkedInKey)&"
authorizationURL += "redirect_uri=\(redirectURL)&"
authorizationURL += "state=\(state)&"
authorizationURL += "scope=\(scope)"
print(authorizationURL)
  • Finally we have to load the request in webview. Make sure that you have passed correct parameters otherwise you are not able to login.
  • To load request in webview you just need to write couple of lines in startAuthorization() method.
1
2
3
// Create a URL request and load it in the web view.
let request = NSURLRequest(URL: NSURL(string: authorizationURL)!)
webView.loadRequest(request)
  • Call startAuthorization() from viewDidLoad().
  • We have to check in webview delegate method that the request URL is the one we are looking for and also we must ensure that the authorization code exist in linkedIn response. Then get authorization code by separating string and call requestForAccessToken(authorizationCode: String) method and pass authorization code as parameter.

 

Step : 5 Request for Access Token

  • Inside requestForAccessToken(authorizationCode: String) method, request for access token using NSMutableURLRequest.
  • Let’s prepare post parameters for access token request
    • grant_type: It’s a standard value that should always be: authorization_code.
    • code: The authorization code acquired in the previous part.
    • redirect_uri: It’s the authorized redirection URL we’ve talked about many times earlier.
    • client_id: The Client Key value.
    • client_secret: The Client Secret Value.
  • Specify grant type and redirect url and set all POST parameters.
1
2
3
4
5
6
7
let redirectURL = "https://com.appcoda.linkedin.oauth/oauth".stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.alphanumericCharacterSet())!
// Set the POST parameters.
var postParams = "grant_type=\(grantType)&"
postParams += "code=\(authorizationCode)&"
postParams += "redirect_uri=\(redirectURL)&"
postParams += "client_id=\(linkedInKey)&"
postParams += "client_secret=\(linkedInSecret)"
  • Set parameters to request body, set HTTPMethod to POST, set content type = application/x-www-form-urlencoded to HTTPHeaderField, After all setting send request.
  • You will receive access token in response, store it in NSUserDefault and dismiss view controller.
  • Full code snippet for requestForAccessToken(authorizationCode: String) method given below.
1
2
func requestForAccessToken(authorizationCode: String) {
let grantType = "authorization_code"

let redirectURL = “https://com.test.LinkedIn/oauth”.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.alphanumericCharacterSet())!

// Set the POST parameters.
var postParams = “grant_type=\(grantType)&”
postParams += “code=\(authorizationCode)&”
postParams += “redirect_uri=\(redirectURL)&”
postParams += “client_id=\(linkedInKey)&”
postParams += “client_secret=\(linkedInSecret)”

// Convert the POST parameters into a NSData object.
let postData = postParams.dataUsingEncoding(NSUTF8StringEncoding)

// Initialize a mutable URL request object using the access token endpoint URL string.
let request = NSMutableURLRequest(URL: NSURL(string: accessTokenEndPoint)!)

// Indicate that we’re about to make a POST request.
request.HTTPMethod = “POST”

// Set the HTTP body using the postData object created above.
request.HTTPBody = postData

// Add the required HTTP header field.
request.addValue(“application/x-www-form-urlencoded;”, forHTTPHeaderField: “Content-Type”)

// Initialize a NSURLSession object.
let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())

// Make the request.
let task: NSURLSessionDataTask = session.dataTaskWithRequest(request) { (data, response, error) -> Void in
// Get the HTTP status code of the request.
let statusCode = (response as! NSHTTPURLResponse).statusCode

if statusCode == 200 {
// Convert the received JSON data into a dictionary.
do {
let dataDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)

let accessToken = dataDictionary[“access_token”] as! String

NSUserDefaults.standardUserDefaults().setObject(accessToken, forKey: “LIAccessToken”)
NSUserDefaults.standardUserDefaults().synchronize()

dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.dismissViewControllerAnimated(true, completion: nil)
})
}
catch {
print(“Could not convert JSON data into a dictionary.”)
}
}
}

task.resume()
}

Step : 6 Check for Existance of Access Token

  • Now in your ViewController.swift file check for Existance of access token and if it already exist then no need to ask user to login, so disable Login with LinkedIn Button and enable Get Profile Button.
1
2
3
4
5
6
func checkForExistingAccessToken() {
if NSUserDefaults.standardUserDefaults().objectForKey("LIAccessToken") != nil {
btnSignIn.enabled = false
btnGetProfileInfo.enabled = true
}
}
  • Call checkForExistingAccessToken() method from viewWillAppear()

Step : 7 Fetching the user profile

  • On Get Profile Details button tap request for user profile detail.
  • For that you we have to make GET request to the linkedIn server by using access token asking for user’s profile detail.
  • You have to pass required parameters name within URL inside bracket for example,

https://api.linkedin.com/v1/people/~:(id,public-profile-url,first-name,last-name,email-address)?format=json

Here id, public-profile-url, first-name, last-name, email-address are parameters name. If you want more detail then you can pass respecting parameter. You can find list of parameters here (https://developer.linkedin.com/docs/fields/basic-profile).

  • After getting success in REST API response then get all detail from dictionary and display it in specific label.
  • Full code snippet for getProfileInfo method is given below:
1
2
3
4
@IBAction func getProfileInfo(sender: AnyObject) {
if let accessToken = NSUserDefaults.standardUserDefaults().objectForKey("LIAccessToken") {
// Specify the URL string that we'll get the profile info from.
let targetURLString = "https://api.linkedin.com/v1/people/~:(id,public-profile-url,first-name,last-name,email-address)?format=json"

// Initialize a mutable URL request object.
let request = NSMutableURLRequest(URL: NSURL(string: targetURLString)!)

// Indicate that this is a GET request.
request.HTTPMethod = “GET”

// Add the access token as an HTTP header field.
request.addValue(“Bearer \(accessToken)”, forHTTPHeaderField: “Authorization”)

// Initialize a NSURLSession object.
let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())

// Make the request.
let task: NSURLSessionDataTask = session.dataTaskWithRequest(request) { (data, response, error) -> Void in
// Get the HTTP status code of the request.
let statusCode = (response as! NSHTTPURLResponse).statusCode

if statusCode == 200 {
// Convert the received JSON data into a dictionary.
do {
let dataDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)
print(“response dictionary ::: \(dataDictionary)”)

dispatch_async(dispatch_get_main_queue(), { () -> Void in
if let profileURLString = dataDictionary[“publicProfileUrl”] {
self.lblPublicUrl.text = profileURLString as? String
}
if let firstName = dataDictionary[“firstName”] {
self.lblFirstName.text = firstName as? String
}
if let lastName = dataDictionary[“lastName”] {
self.lblLastName.text = lastName as? String
}
if let userId = dataDictionary[“id”] {
self.lblId.text = userId as? String
}
if let email = dataDictionary[“emailAddress”] {
self.lblEmail.text = email as? String
}
})
}
catch {
print(“Could not convert JSON data into a dictionary.”)
}
}
}

task.resume()
}
}

Summary :

All you have to done for LinkedIn Login and fetch user profile….

  1. Create application in LinkedIn Developer.
  2. Set authorization redirect URL and default application permission.
  3. Prepare request to get authorization code and load it in webview.
  4. Get Access Token using authorization code and store it in user default.
  5. Using Access token get user profile info.

 

Brevity

About Admin

Brevity Software provides services such as : Web design and development, Mobile application development, Web application development, Travel portal development, Event management systems, Transport & Logistics Software, Enterprise Mobility Solutions, eCommerce & M Commerce application and many more.

2 thoughts on “Integrating LinkedIn Sign In with iOS Application

  1. Its a great article, it will be easier to user to Integrating LinkedIn sign in with iOS Application, Thanks for sharing such article.

  2. A person necessarily lend a hand to make seriously articles I’d state.
    That is the first time I frequented your web page and so far?
    I surprised with the research you made to create this actual submit extraordinary.
    Fantastic task!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>