How to add Spotify Login button to your iOS app using Swift
- November 06, 2019
- John Codeos
Today, I’m going to show you how to add the Spotify Login Button to your iOS easily using a ViewController with a WebView and making an HTTP request.
You don’t need any 3rd party library from Spotify to implement this.
Lets get started!
First, go to developer.spotify.com/dashboard and login with your Spotify account. (You don’t need Spotify Premium to have access to Spotify for Developers.)
Next, create a new app by pressing the box.
In the new window, fill in all the requirement fields, like app name, description e.t.c., and press NEXT.
… next step, choose if it’s a commercial app or not. In this example, the answer is NO.
Check the boxes and press SUBMIT.
Once you get to the dashboard of your app, go to EDIT SETTINGS.
In the new window, add your website (if you have one), as Redirect URIs add the name of your app and at the end add :// , for this example is spotifysigninexample://, and lastly, in Bundle IDs add your Bundle Bundle Identifier and press SAVE
Creating the Spofity Login 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 spotifyLoginBtn and spotifyLoginBtnAction.
Create a new swift file to put the Constants.
Paste the following code inside.
Replace the Client ID and Redirect URI with yours.
Here, we use the scope user-read-email to get the user’s email address. You can see more about other scopes, here.
Next, create a ViewController with a WebView.
Here, 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 access token using the .range method.
Finally, close the ViewController with the WebView and use the access token to get the user’s ID, username, 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!