Skip to content

Instantly share code, notes, and snippets.

@arirawr
Created January 5, 2018 12:19
Show Gist options
  • Save arirawr/c9220042caff1605fa8eeb929847cfc4 to your computer and use it in GitHub Desktop.
Save arirawr/c9220042caff1605fa8eeb929847cfc4 to your computer and use it in GitHub Desktop.
Spotify Authentication with iOS SDK in Swift
//
// ViewController.swift
// iOSSDKSwift
//
// Created by Arielle Vaniderstine on 2017-04-06.
// Copyright © 2017 Arielle Vaniderstine. All rights reserved.
//
import UIKit
class ViewController: UIViewController, SPTAudioStreamingPlaybackDelegate, SPTAudioStreamingDelegate {
var auth = SPTAuth.defaultInstance()!
var session:SPTSession!
var player: SPTAudioStreamingController?
var loginUrl: URL?
@IBOutlet weak var loginButton: UIButton!
@IBAction func loginPressed(_ sender: Any) {
UIApplication.shared.open(loginUrl!, options: [:], completionHandler: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
setup()
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.updateAfterFirstLogin), name: NSNotification.Name(rawValue: "loginSuccessful"), object: nil)
}
func updateAfterFirstLogin () {
loginButton.isHidden = true
let userDefaults = UserDefaults.standard
if let sessionObj:AnyObject = userDefaults.object(forKey: "SpotifySession") as AnyObject? {
let sessionDataObj = sessionObj as! Data
let firstTimeSession = NSKeyedUnarchiver.unarchiveObject(with: sessionDataObj) as! SPTSession
self.session = firstTimeSession
initializePlayer(authSession: session)
}
}
func initializePlayer(authSession:SPTSession){
if self.player == nil {
self.player = SPTAudioStreamingController.sharedInstance()
self.player!.playbackDelegate = self
self.player!.delegate = self
try! player?.start(withClientId: auth.clientID)
self.player!.login(withAccessToken: authSession.accessToken)
print("Player has been initialized")
}
}
func audioStreamingDidLogin(_ audioStreaming: SPTAudioStreamingController!) {
// after a user authenticates a session, the SPTAudioStreamingController is then initialized and this method called
print("logged in")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setup () {
// insert redirect your url and client ID below
let redirectURL = "your-bundle-id://your-scheme" // put your redirect URL here
let clientID = "" // put your client ID here
auth.redirectURL = URL(string: redirectURL)
auth.clientID = clientID
// put your scopes here
auth.requestedScopes = [SPTAuthStreamingScope, SPTAuthPlaylistReadPrivateScope, SPTAuthPlaylistModifyPublicScope, SPTAuthPlaylistModifyPrivateScope, SPTAuthUserLibraryReadScope]
loginUrl = auth.spotifyWebAuthenticationURL()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment