How To Integrate Spotify API With iOS App?

2 min read

I set out to make a social networking application that allowed users to choose musical track found on Spotify and when  someone view other user’s profile it will be visible under profile information with play button. 

This article is about tricks used to get Spotify track without login and installing application on iOS or Android device. Steps to be followed are as below. 

Go to Spotify for Developers using ” https://developer.spotify.com” click on “DASHBOARD” tab, Login into Spotify wherein  you shall find Client ID and Client Secret.

Spotify Demo

Once, you obtain Client ID and Client Secret call “REST “ API of Spotify that helps to get “preview” tracks. Swift language code to  retrieve API is

Spotify Code

Get Spotify token to access other API’s – below is code to create separate class for Spotify token.

import Foundation
import Apollo

let spotifyClientId = "59bc58e3d1544c1081af50eb051f9421"
let spotifyClientSecret = "4f1f4ee82d854c80bc503c33a48720d1"

class SpotifyToken: NSObject {
    
    var currentToken: String?
    
    init(object: String) {
        super.init()
        self.update(object: object)
    }
    
    func update(object: String) {
        currentToken = object
    }
    
    static func currentToken() -> String?
    {
        if let data = UserDefaults.standard.object(forKey: Strings.CurrentSpotifyToken.rawValue) as? String, !data.isEmpty {
            return data
        }
        return nil
        
    }
    static func isAvailable() -> Bool
    {
        if let _ = currentToken() {
            return true
        }
        else {
            return false
        }
    }
    
    static func logout()
    {
        UserDefaults.standard.set(nil, forKey: Strings.CurrentSpotifyToken.rawValue)
        UserDefaults.standard.synchronize()
    }
    
    func saveToDefaults() {
        UserDefaults.standard.set(currentToken, forKey: Strings.CurrentSpotifyToken.rawValue)
        UserDefaults.standard.synchronize()
    }
}

For bearer we need to use Client ID : Client Secret and need to convert to base64 string.

let strBearer = "\(spotifyClientId):\(spotifyClientSecret)".toBase64()
let header = ["Authorization" : "Basic \(strBearer)", "Content-Type" : "application/x-www-form-urlencoded"]
let params = ["grant_type" : "client_credentials"] as [String : AnyObject]
let finalUrl = "https://accounts.spotify.com/api/token" 

AFWrapper.requesting(methodRequest: .post, URLString: finalUrl, header: header, parameters: params, onSuccess: { (object) in
             let responseData = object as? NSDictionary
             if let error = responseData?.object(forKey: "error") {
                  let errDict = error as? NSDictionary
                  let description = errDict?.object(forKey: "error_description") as? String
                  if description != nil {
                      self.hideLoader()
                      self.displayTost(strMessage: description!)
                   }
              } else {
                   if ((responseData?.object(forKey: "access_token")) != nil) {
                        let token = responseData?.object(forKey: "access_token") as! String
                        let sp_token = SpotifyToken(object: token)
                        sp_token.saveToDefaults()
                    }
                }
        }) { (error) in
             self.hideLoader()
        }

Code To GET Popular Tracks

let finalUrl = https://api.spotify.com/v1/playlists/37i9dQZEVXbMDoHDwVN2tF 
let header = ["Authorization" : "Bearer \(SpotifyToken.currentToken() ?? "")"]

Code to GET tracks using search keywords: search key words include artist name, album, and song name and preview URL.

var finalUrl = "https://api.spotify.com/v1/search?q=\(searchText)&type=track&limit=50" 
finalUrl = finalUrl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)! 
         
let header = ["Authorization" : "Bearer \(SpotifyToken.currentToken() ?? "")"]

Gaps in using above code 

🖉 Preview URL contains 30 seconds part of original song. 

🖉 Validity for Spotify token (for Client credential) is only for an hour.

iOS Team

At Blue Whale Apps, Our iOS team creates beautiful, reliable best-in-class mobile experiences for iOS.

Subscribe To Our Newsletters

Get our stories in your inbox

Articles, news, infographics, tips and expert talks about mobile apps.