Created
April 2, 2020 18:02
-
-
Save zallanx/43f0a2db0451bf1cbcf98e26f49a98c7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
import SwiftyJSON | |
import AVFoundation | |
import SVProgressHUD | |
let TheSpotifyManager = SpotifyManager.shared | |
class SpotifyManager: NSObject, BaseMusicManager, SPTSessionManagerDelegate { | |
static let shared = SpotifyManager() | |
var appRemoteDelegate: SPTAppRemoteDelegate? | |
var sessionDelegate: SPTSessionManagerDelegate? | |
lazy var configuration: SPTConfiguration = { | |
SPTConfiguration(clientID: AppConstants.Spotify.CLIENT_ID, redirectURL: AppConstants.Spotify.REDIRECT_URI) | |
}() | |
var accessToken: String? { | |
get { | |
return self.appRemote.connectionParameters.accessToken | |
} | |
} | |
lazy var appRemote: SPTAppRemote = { | |
let appRemote = SPTAppRemote(configuration: self.configuration, logLevel: .debug) | |
appRemote.delegate = self.appRemoteDelegate | |
return appRemote | |
}() | |
lazy var sessionManager: SPTSessionManager = { | |
if let tokenSwapURL = URL(string: "LINK_TO_TOKEN_URL"), //ensure that this is supplied | |
let tokenRefreshURL = URL(string: "LINK_TO_TOKEN_REFRESH_URL") { //ensure that this is supplied | |
self.configuration.tokenSwapURL = tokenSwapURL | |
self.configuration.tokenRefreshURL = tokenRefreshURL | |
self.configuration.playURI = nil//spotify:playlist:\(AppConstants.Spotify.PLAYLIST_ID)" | |
} | |
let manager = SPTSessionManager(configuration: configuration, delegate: self.sessionDelegate) | |
return manager | |
}() | |
fileprivate func sendRequest(playlist:Playlist, url: String, completion:@escaping ((Playlist?, Error?) -> Void)) { | |
TheSpotifyWebServiceAPI.sendGetRequestWithHeader(url) { (response, error) in | |
SVProgressHUD.dismiss() | |
if (response != nil) { | |
if let dictResponse = JSON(response!).dictionary { | |
if let dictError = dictResponse["error"]?.dictionary { | |
let strErrMsg = dictError["message"]?.string ?? AppConstants.SomethingWentWrong | |
SVProgressHUD.showError(withStatus: strErrMsg) | |
SVProgressHUD.dismiss(withDelay: 3) | |
} else if let arrItems = dictResponse["items"]?.array { | |
// if playlist == nil { | |
// playlist = SpotifyPlaylist.init(withDict: dictResponse) | |
// } | |
for nIdx in 0..<arrItems.count { | |
if let eachItem = arrItems[nIdx].dictionary, let eachTrack = eachItem["track"]?.dictionary { | |
let track = SpotifyTrack.init(from: eachTrack) | |
playlist.tracks.append(track) | |
} | |
} | |
if let nextUrl = dictResponse["next"]?.string { | |
self.sendRequest(playlist: playlist, url: nextUrl, completion: completion) | |
} else { | |
completion(playlist, nil) | |
} | |
} else { | |
SVProgressHUD.showError(withStatus: AppConstants.SomethingWentWrong) | |
SVProgressHUD.dismiss(withDelay: 3) | |
completion(nil, nil) | |
} | |
} | |
} else { | |
SVProgressHUD.showError(withStatus: AppConstants.SomethingWentWrong) | |
SVProgressHUD.dismiss(withDelay: 3) | |
completion(nil, nil) | |
} | |
} | |
} | |
func fetchPlaylist(_ playlistID: String, completionHandler completion:@escaping ((Playlist?, Error?) -> Void)) { | |
let playlist = SpotifyPlaylist.init(withDict: ["id":playlistID]) | |
let url = "https://api.spotify.com/v1/playlists/\(playlistID)/tracks" | |
sendRequest(playlist: playlist, url: url, completion: completion) | |
} | |
func followArtist(_ artistId: String) { | |
let url = "https://api.spotify.com/v1/me/following?type=artist&ids=\(artistId)" | |
TheSpotifyWebServiceAPI.sendPutRequestWithHeader(url, params: nil, completion: { (result, error) in | |
print("Following an artist result - ", result ?? "No result", error ?? "No error") | |
}) | |
} | |
func requestAuthorization(appRemoteDelegate: SPTAppRemoteDelegate) { | |
let scope: SPTScope = [.appRemoteControl, .userFollowModify, .streaming] | |
SpotifyManager.shared.sessionManager.delegate = self | |
SpotifyManager.shared.appRemote.delegate = appRemoteDelegate | |
SpotifyManager.shared.sessionManager.initiateSession(with: scope, options: AuthorizationOptions.default) | |
SVProgressHUD.show() | |
} | |
func saveToDefaults() { | |
// UserDefaults.standard.set(SpotifyManager.shared.appRemote.connectionParameters.accessToken, forKey:"SpotifyAccessTOken") | |
} | |
func restoreFromDefaults() { | |
// if let accessToken = UserDefaults.standard.value(forKey: "SpotifyAccessTOken") as? String { | |
// SpotifyManager.shared.appRemote.connectionParameters.accessToken = accessToken | |
// } | |
} | |
} | |
extension SpotifyManager { | |
func sessionManager(manager: SPTSessionManager, didFailWith error: Error) { | |
print("sessionManager didFailWith ", error) | |
SVProgressHUD.dismiss() | |
} | |
func sessionManager(manager: SPTSessionManager, didRenew session: SPTSession) { | |
print("sessionManager didRenew ", session) | |
SVProgressHUD.dismiss() | |
} | |
func sessionManager(manager: SPTSessionManager, didInitiate session: SPTSession) { | |
print("sessionManager didInitiate ", session) | |
DispatchQueue.main.async { | |
SVProgressHUD.dismiss() | |
SpotifyManager.shared.appRemote.connectionParameters.accessToken = session.accessToken | |
SpotifyManager.shared.appRemote.connect() | |
SpotifyManager.shared.saveToDefaults() | |
// MARK: following the artist automatically | |
SpotifyManager.shared.followArtist(AppConstants.Spotify.ARTIST_ID) | |
} | |
} | |
func sessionManager(manager: SPTSessionManager, shouldRequestAccessTokenWith code: String) -> Bool { | |
return true | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment