How to add GitHub Login button to your iOS app using Swift
- December 16, 2019
- John Codeos
Today, I’ll show you how to implement the ‘Log in with GitHub’ button into your iOS app.
We’re going to use 3-legged Authorization(OAuth) 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 an HTTP request to https://api.github.com/user
Lets get started!
First, we need to create the Client ID and Client Secret on the GitHub website.
Go to https://github.com/settings/developers and press the Register a new application button.
Fill the required fields and press Register application.
On the new page, you’ll see the Client ID and Client Secret we going to use later.
Creating the GitHub Login Button
Create an UIButton in your ViewController and make an Outlet and an Action connection to your swift file. In this example, we called it githubLoginBtn and githubLoginBtnAction.
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.
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, display name, email and profile pic URL using HTTP request.
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!