Code Monkey home page Code Monkey logo

spotifykit's Introduction

SpotifyKit

A Swift client for Spotify's Web API.

Build Status Version License Platform

Installation

SpotifyKit is available through CocoaPods. To install it, simply add the following line to your Podfile:

pod "SpotifyKit"

Initialization

You can easily create a SpotifyKit helper object by providing your Spotify application data.

let spotifyManager = SpotifyManager(with:
    SpotifyManager.SpotifyDeveloperApplication(
        clientId:     "client_id",
        clientSecret: "client_secret",
        redirectUri:  "redirect_uri"
    )
)

The token data gathered at authentication moment is automatically saved in a secure preference with Keychain.

Authentication

This is arguably the trickiest step. At your app launch, you should call authorization method like this:

spotifyManager.authorize()

It sends a request of authorization for the user's account, that will result in a HTTP response with the specified URL prefix and the authorization code as parameter. The method automatically skips the process if a saved token is found.

Then, in order to complete authentication and obtain the token, you must setup a URL scheme (in Info.plist file of your app) and catch the code like this:

iOS

// MARK: in your AppDelegate.swift file

/**
 Catches URLs with specific prefix ("your_spotify_redirect_uri://")
 */
func application(_ application: UIApplication, handleOpen url: URL) -> Bool {
    spotifyManager.saveToken(from: url)

    return true
}

MacOS

/**
 Registers the URL watcher
 */
NSAppleEventManager.shared().setEventHandler(self,
    andSelector: #selector(handleURLEvent),
    forEventClass: AEEventClass(kInternetEventClass),
    andEventID: AEEventID(kAEGetURL))

/**
 Catches URLs with specific prefix ("your_spotify_redirect_uri://")
 */
func handleURLEvent(event: NSAppleEventDescriptor,
                    replyEvent: NSAppleEventDescriptor) {
	if	let descriptor = event.paramDescriptor(forKeyword: keyDirectObject),
		let urlString  = descriptor.stringValue,
		let url        = URL(string: urlString) {
		spotifyManager.saveToken(from: url)
	}
}

Now SpotifyKit is fully authenticated with your user account and you can use all the methods it provides.

Usage

All methods send HTTP request through URLSession API and report the results with simple callbacks

Find

Finds tracks (as in this example), albums or artists in Spotify database:

// Signature
public func find<T>(_ what: T.Type,
                    _ keyword: String,
                    completionHandler: @escaping ([T]) -> Void) where T: SpotifySearchItem

// Example
spotifyManager.find(SpotifyTrack.self, "track_title") { tracks in
	// Tracks is a [SpotifyTrack] array
	for track in tracks {
        print("URI:    \(track.uri), "         +
              "Name:   \(track.name), "        +
              "Artist: \(track.artist.name), " +
              "Album:  \(track.album.name)")
    }
}

get() and library() functions are also available for retrieving a specific item or fetching your library's tracks, albums or playlists.

User library interaction

Save, delete and check saved status for tracks in "Your Music" playlist

// Save the track
spotifyManager.save(trackId: "track_id") { saved in
    print("Saved: \(saved)")
}

// Check if the track is saved
spotifyManager.isSaved(trackId: "track_id") { isSaved in
    print("Is saved: \(isSaved)")
}

// Delete the track
spotifyManager.delete(trackId: "track_id") { deleted in
    print("Deleted: \(deleted)")
}

Supported Spotify items

The items are automatically decoded from JSON, by conforming to Swift 4 "Decodable" protocol.

Generic item

The protocol which is inherited by all items, including common properties

public protocol SpotifyItem: Decodable {

	var id:   String { get }
	var uri:  String { get }
	var name: String { get }
}

public protocol SpotifySearchItem: SpotifyItem {
	// Items conforming to this protocol can be searched
}

public protocol SpotifyLibraryItem: SpotifyItem {
	// Items conforming to this protocol can be contained in user's library
}

User

public struct SpotifyUser: SpotifySearchItem {

	public var email:  String?

	// URI of the user profile picture
	public var artUri: String
}

Track

public struct SpotifyTrack: SpotifySearchItem, SpotifyLibraryItem {

	public var album:  SpotifyAlbum?
	public var artist: SpotifyArtist
}

Album

public struct SpotifyAlbum: SpotifySearchItem, SpotifyLibraryItem, SpotifyTrackCollection {

	// The tracks contained in the album
	public var collectionTracks: [SpotifyTrack]?

	public var artist: SpotifyArtist

	// The album's cover image
	public var artUri: String
}

Playlist

public struct SpotifyPlaylist: SpotifySearchItem, SpotifyLibraryItem, SpotifyTrackCollection {

	// The tracks contained in the playlist
	public var collectionTracks: [SpotifyTrack]?
}

Artist

public struct SpotifyArtist: SpotifySearchItem {
	// Artist has no additional properties
}

Examples

  • iOS and macOS sample projects are available in this repository
  • Muse

spotifykit's People

Contributors

xzzz9097 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

spotifykit's Issues

Accepting pull requests?

Hello! I have been using SpotifyKit for my own personal project, but saw it didn't meet all of my use cases. So of course I added some of my own needed features such as spotify pagination, auth scopes,and completion handler for after authentication (just to name a few). I would be happy to clean it up a bit and submit a request. It's a bit messy but feel free to take a look here

Future development question

Thanks for this library, I was playing around with it and found it very useful.

So far I had the following problems:

  • missing fields in data parsing (ex. external_urls, external_ids etc.)
  • error handling seems to be missing on malformed responses
  • Unaccessible private properties on data models (ex. images)
  • Missing data models (ex. category)

Overall the parsing contains very good ideas with generic models and it was a great way getting into Decodables.

I mainly used SpotifyItems, cleaned it up, added a generic collection item that could be reused across all responses containing paginated lists (parsing all fields: limit, offset, total, prev, next) and some readability improvements.

My question:
Is there a plan to improve this library in the future?
Would pull requests be considered?

Many thanks.

Podfile integration issues

Hi,

Thanks for the nice framework. A couple issues:

I create a fresh single view project using the latest Xcode, compiled for iOS12. I then integrated into this project using:

pod 'SpotifyKit'

I receive a compilation error, and the framework appears in red within the project. This is using the master branch 0.0.6

I instead grabbed the source and placed in the project (in lieu of pod file integration) and receive two warnings in iOS12.

'unarchiveObject(with:)' was deprecated in iOS 12.0: Use +unarchivedObjectOfClass:fromData:error: instead

These occur on lines 35 and 55 in file Keychain.swift

Would appreciate if you could guid me on proper Pod integration, and whether I am pointing to the proper version. As I noticed you have a Swift4 branch, though your comments in the main branch allude to swift4 integration.

Thanks again.

Using SpotifyKit to export playlists

I'm a complete beginner to Swift but wanted to create an app that exports playlists to Spotify based on mood. I have a random array of Spotify song URI strings but for some reason, I cannot 1) connect the user to my app (ie: based on your test code, the picture and information do not update) and 2) figure out how to export a playlist.

If you could briefly explain how I could do that, I would really appreciate it.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.