Play Music in Spotify app without using Spotify SDK in swift
Recently, I was working on a project that would involve playing music on the Spotify app. At first, I thought it is necessary to have Spotify SDK but for just opening and playing a track in Spotify, we don't need SDK. From my observation, I have observed that Spotify SDK doesn't have the utility to get the track information from Spotify API. So what if we only have song name, artist name and we don't have a Spotify track id that is required for playing music in the Spotify app. if this is the use case of your task, then you have come right place. This post will go through the process of setting up an environment that is required to play music in the Spotify app.
Step 1:
First You’ll need to create a developer account and register your account. You can click here to signup. Once you are in the account you’re going to want to create a new client ID.
Step 2:
We now need to update some of the settings in your client on the dashboard. Click the “Edit Settings” button in the top right of the developer dashboard and you should see something similar to:
Step 3:
let update the bundle id of the ios app as com.company.app (you will find this in your iOS project under General ->Identity).
Step 4:
Save your client id and client secret for later. We’ll need those guys.
Step 5:
Build a utility class Spotify Manager which contains API calls required to get track information of music. For this, we need to get an access token using the client credentials
let url = "https://accounts.spotify.com/api/token"var headers = ["Content-Type":"application/x-www-form-urlencoded"]if let header = Alamofire.Request.authorizationHeader(user: "spotify_client_id", password: "spotify_client_secret") {headers[header.key] = header.value}Alamofire.request(url, method: .post, parameters: ["grant_type":"client_credentials"], encoding: URLEncoding.default, headers: headers)
.authenticate(user: "spotify_client_id" , password: "spotify_client_secret").responseJSON { response in if let json = response.result.value { let dict = json as! [String: Any] if let access_token = dict["access_token"] {
successCallback(access_token as! String)
}
}
}
Step 6:
Next, we need to get track information using access_token which we got above.
public func find(_ keyword: String, artist: String, completionHandler: @escaping ([SpotifyTrack]) -> Void) { let urlRequest = self.createSearchRequest(with: keyword, artist: artist) let task = URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in guard error == nil, let urlResponse = response as? HTTPURLResponse, urlResponse.statusCode == 200 else { completionHandler([]) return } if let results = try? JSONDecoder().decode(SpotifyFindResponse<SpotifyTrack>.self, from: data!).results.items {
completionHandler(results)
}
}
task.resume()
}func createSearchRequest(with term: String, artist: String = "") -> URLRequest { let urlString = "https://api.spotify.com/v1/search?q=track:\(term) artist:\(artist)&type=track,artist" let url = URL(string:urlString.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)!)! // Create and configure the `URLRequest`.
var request = URLRequest(url: url as URL)
request.httpMethod = "GET"
request.addValue("Bearer \(access_token)", forHTTPHeaderField: "Authorization")
return request
}
Step 7:
Add LSApplicationQueriesSchemes to the following to be able to open the Spotify app from your app.
Step 8:
after getting the track URI simply navigates to URI using UIApplication.shared.open(trackURI, options: [:], completionHandler: nil)
this will start playing the song in the Spotify app for you
let spotifyManager = SpotifyManager()spotifyManager.getTrack(title: songTitle, artist: songArtist) { (track: SpotifyTrack) inlet url = URL(string: "\(track.uri)")!if UIApplication.shared.canOpenURL(url) {
// opens spotify app and start playing song
UIApplication.shared.open(url, options: [:], completionHandler: nil)} else {
// navigate user to app store spotify page if user doesnt have spotify app installed
self.showAppStoreInstall()
}
}
Hope this would be useful. I have spent some significant amount of time setting up the Spotify SDK. But in the end for this use case, it's not even required. Happy Coding!