How to add ‘Sign In with LinkedIn’ Button to your iOS app using Swift
- October 28, 2019
- John Codeos
Today, I’ll show you how to implement the ‘Sign In with LinkedIn’ button into your iOS app.
We’re going to use the 3-legged OAuth method to get the authorization code and exchange it later for the access token. Using the access token, we’ll be able to get user’s information and email address making two HTTP GET requests, one to get user’s id, first name, last name and profile pic URL, and one to get the email address.
Lets get started!
First, create a LinkedIn account if you don’t already have one.
Go to https://www.linkedin.com/developers and click on the Create app button.
Fill in the required fields.
To create an app, you need to add your company’s page.
If you’re not a company or you want to avoid this step, just add a random company. It doesn’t cause any problem.
Next, go to the Auth tab of your app and add your redirect URL.
Creating the ‘Sign In with LinkedIn’ Button
First, create an UIButton in your ViewController and make an Outlet and an Action connection to your swift file. In this example, we called it linkedInLoginBtn and linkedInLoginBtnAction.
Create a new swift file to put the Constants.
Paste the following code inside.
Replace the Client ID, Client Secret and Redirect URI with yours.
Create a new swift file with a name LinkedInEmailModel and paste the following code.
Create another one with a name LinkedInProfileModel.
These are the models you’ll need later to get user’s profile info and email address from the HTTP requests.
Next, create a ViewController with a WebView.
The user puts the email and password and gives access to the app.
After giving access, the webView gets the URL request, using the method decidePolicyFor from the WKNavigationDelegate.
Then, from the URL request, get the authorization code using the .range method and exchange it for the access token.
Finally, use the access token to get the user’s ID, first name, last name, email and profile pic URL using HTTP request.
That’s it! Done!
You can find the final project here
If you have any questions feel free to DM me on Twitter @johncodeos or leave a comment below!