Swift framework for authenticating with the Spotify API

Overview

SpotifyLogin - Swift 5 Framework for authenticating with the Spotify API

Build Status Version Carthage compatible

SpotifyLogin

SpotifyLogin is a Swift 5 Framework for authenticating with the Spotify API.

Usage of this framework is bound under the Developer Terms of Use.

Usage

Disclaimer

SpotifyLogin is appropriate for prototyping and non-commercial use only.

If your app is meant for commercial production usage, SpotifyLogin can NOT be used.

Compatibility

SpotifyLogin requires Xcode 10.2+. It is compatible with iOS 9 or later.

Pre-requisites

You will need to register your app in the Developer Portal.

Make sure to use a unique redirect url and to supply the bundle ID from your app.

After registering, you will receive a client ID and a client secret.

Set up SpotifyLogin

Set up SpotifyLogin using any of the methods detailed below (Cocoapods / Carthage / manually).

Set up info.plist

In Xcode, go to your app's target and select the Info tab. At the bottom, of the screen you will find URL Types, expand the list and create a new one.

Set up info.plist

Add the app's identifer as the Identifier and the redirect url scheme in URL schemes.

Additionally, you will need to add "spotify-action" to the LSApplicationQueriesSchemes key: LSApplicationQueriesSchemes

Set up your AppDelegate

Add the following to your app delegate:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    SpotifyLogin.shared.configure(clientID: <#T##String#>, clientSecret: <#T##String#>, redirectURL: <#T##URL#>)
    return true
}

func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
    let handled = SpotifyLogin.shared.applicationOpenURL(url) { (error) in }
    return handled
}

Check if a user is logged in.

You can retrieve an access token and check if a user is logged in by:

SpotifyLogin.shared.getAccessToken { (accessToken, error) in
    if error != nil {
        // User is not logged in, show log in flow.
    }
}

This also automatically takes care of renewing expired tokens.

Log in / Log out

To add the default log in button:

let button = SpotifyLoginButton(viewController: self, scopes: [.streaming, .userLibraryRead])
self.view.addSubview(button)

The scopes define the set of permissions your app will be able to use. For more information about available scopes, see Scopes Documentation

To log out:

SpotifyLogin.shared.logout()

Update UI after successful log in.

The log in flow is completed in applicationOpenURL. To respond to a successful log in, you can add your own code in the completion handler or respond to the SpotifyLoginSuccessful notification:

NotificationCenter.default.addObserver(self, selector: #selector(loginSuccessful), name: .SpotifyLoginSuccessful, object: nil)

Additional features

Access the current user's username:

let username = SpotifyLogin.shared.username

To trigger the log in flow from a custom action:

SpotifyLoginPresenter.login(from: self, scopes: [.streaming, .userLibraryRead])

Setting up

Setting up with CocoaPods

source 'https://github.com/CocoaPods/Specs.git'
pod 'SpotifyLogin', '~> 0.1'

Setting up with Carthage

Carthage is a decentralized dependency manager that automates the process of adding frameworks to your Cocoa application.

You can install Carthage with Homebrew using the following command:

$ brew update
$ brew install carthage

To integrate SpotifyLogin into your Xcode project using Carthage, specify it in your Cartfile:

github "spotify/SpotifyLogin"

Code of conduct

This project adheres to the Open Code of Conduct. By contributing, you are expected to honor this code.

Additional information

Spotify Developer Portal | API Reference

Comments
  • Change BPM value of Spotify Song Swift

    Change BPM value of Spotify Song Swift

    I am trying to build an application that plays Spotify songs. I am really confused about how to change BPM(Beats Per Minute,) value of Spotify songs. First Step: Login through Spotify. Second Step: Get Current user all album. Third Step: get album track. Last Step: play track. I have done All step with Spotify Delegates. but I want to change the BPM value of the track. Can someone please explain to me how to change the BPM value?

    opened by shamdass 6
  • Reduce code duplication dispatching to main queue

    Reduce code duplication dispatching to main queue

    This PR reduces duplicated calls when dispatching completion handlers back to the main queue.

    We can now pass a generic result type and en error object that is used in the majority of cases to a private helper function that takes over the job of calling the GCP API.

    opened by Broich 5
  • Allow show_dialog to be false

    Allow show_dialog to be false

    If you are filing a bug report, please include information for the topics below. Also, please make sure to only report one bug/feature request/question per issue.

    Description

    show_dialog is hardcoded to true. It should be able to be set by the developer.

    Versions

    1.0.6

    Severity

    Minor

    enhancement 
    opened by arirawr 2
  • Extract the keychain wrapper code and add tests for it

    Extract the keychain wrapper code and add tests for it

    The problem: the current code that interacts with the Keychain fails to remove the stored session data. This is not a big issue because the session username is removed from UserDefaults thus the stored data can't be retrieved, however it is still not good.

    How to know that the Keychain functions failed? - Currently those do not report success/failure and are not tested. The SpotifyLogin tests only check that the stored session username is saved/removed but not that the data associated with it is securely stored. We need to add tests that verify this in order to be sure that the app login flow works correctly.

    Solution: I split the Keychain-related code from the session-specific methods so that those could be tested. The only change to that code is making it return boolean success/failure indicating flag.

    The diff is a bit weird although I used git mv to rename the Keychain file.. Anyway, the first commit does not modify the SpotifyLogin functionality, it just extracts the Keychain-related code to its own class and renames the Keychain class to SessionLocalStorage which reflects better what it does (save / load / remove).

    Then the next two commits setup the Sample project to include and actually execute a test which check if the keychain values are stored/removed properly. I added these tests to the Sample project because I was running into problems to interact with the Keychain APIs from the test target of the SpotifyLogin framework (getting OSStatus -34018 all the time, looks like it is a known issue).

    Lastly, I will push another commit that fixes the problem and the tests should pass šŸ¤ž

    opened by nataliq 2
  • Need queryScheme to check canOpenURL

    Need queryScheme to check canOpenURL

    Hi, I'm reading the source code https://github.com/spotify/SpotifyLogin/blob/master/Sources/SpotifyLoginPresenter.swift, this line

    UIApplication.shared.canOpenURL(appAuthenticationURL)
    

    but as iOS 9+, there is new requirement https://useyourloaf.com/blog/querying-url-schemes-with-canopenurl/ that LSApplicationQueriesSchemes is needed.

    I think we should state this in the README

    opened by onmyway133 2
  • update swift 5, add missing scopes, remove warnings

    update swift 5, add missing scopes, remove warnings

    As for the Swift 5 update: I couldn't find the exact compatibility informations, therefore maybe the Compatibility section in the readme needs to be changed, too. Ok, with the help of the CI, I discovered that you need a minimum of Xcode 10.2 to run Swift 5 projects.

    Furthermore I fixed some obvious compiler warnings and added the missing scopes for App Remote Control and Image Upload.

    opened by tomaculum 1
  • Fix weak SafariDelegate reference in SpotifyLoginPresenter

    Fix weak SafariDelegate reference in SpotifyLoginPresenter

    Xcode throws the Swift compiler warning: Instance will be immediately deallocated because property 'delegate' is 'weak' when using SpotifyLogin.

    By switching the delegate to a strong reference, it stops throwing the compiler warning.

    opened by AFRUITPIE 1
  • SpotifyLogin does not work in iOS 12

    SpotifyLogin does not work in iOS 12

    If you are filing a bug report, please include information for the topics below. Also, please make sure to only report one bug/feature request/question per issue.

    Description

    A concise description of what the problem is. Using the correct values for Client ID, Client Secret, Redirect URL, and following the tutorial exactly, the error "Safari cannot open the page because the address is invalid" is thrown on iOS 12.

    Versions

    iOS SDK version: iOS 12 (-sdk iphoneos12.0) Spotify app version (if native SSO flow is involved)

    Severity

    Trivial, Minor, Major, Catastrophic

    Major

    Steps to Reproduce

    1. Step by step instructions on how to reproduce this bug. Install iOS 12 developer beta 6, complete the sample included in the repo. During login at the "cancel" or "okay" screen, both buttons cause "Safari cannot open the page because the address is invalid."
    2. The more detailed your list of instructions, the easier it is for the developer to track down the problem!

    Actual behaviour

    Describe what happens when you perform the steps above. Safari closes and app is logged in

    Expected behaviour

    Describe what you expected to happen when performing the steps above. Error: "Safari cannot open the page because the address is invalid."

    Logs

    Please include any relevant log output that might assist in tracking down the problem. No logs

    opened by AFRUITPIE 1
  • How renew Spotify session

    How renew Spotify session

    Hi, I am implementing your library in my app and I have a little problem. When my application is launched I'll want to restore my stored session then check if it's valid and renew it if necessary. I want also renew my access_token when i launch my application in a new device but I want to avoid interaction by the user. Then i would like store the refresh_token in my online DB. But i can't access to the refresh token and I can't find a function to refresh my access_token with a refresh_token. Do you have an idea of how to do it with your library ? Thanks

    opened by baillyjamy 1
  • Get a session

    Get a session

    Is there a way that the SpotifyLogin pod can work with the SPTAuthentication class from the iOS SDK. Specifically I am curious about setting the session in SPTAuthentication from Spotify Login.

    opened by RudyB 1
  • Marks singleton initialiser as private

    Marks singleton initialiser as private

    Assuming that we want consumers of the API to go through the shared instance I suggest marking the object's initialiser as private.

    It's not a big problem in different modules at all but maybe still worth being explicit about it?

    opened by Broich 1
  • Sample Project not working for me

    Sample Project not working for me

    I downloaded the sample project and added in my redirectURL, client id and client secret. Added the correct URL type in the info tab. The app launches, I press the login button, it takes me to Spotify and I authorize it successfully and then takes me back to the login screen and nothing else happens. The loginSuccessful() method is never called. Please help

    opened by CodeRed-Tim 1
  • SpotifyLoginSuccessful notification gets called even when you login from SnapSDK

    SpotifyLoginSuccessful notification gets called even when you login from SnapSDK

    I have snapchat and spotify social logins implements inside my app and the SpotifyLoginSuccessful notification is called after coming back to app from snapchat login. On debugging i found applicationOpenURL inside SpotifyLogin.swift is posting that notification. For now i have setup a check if url does not contain snap-kit only then the rest of the function will be called otherwise returned false. Please fix this issue, thank you the library nonetheless it is working great!

    Snap library link - https://github.com/Snapchat/login-kit-sample/tree/master/ios/Pods/SnapSDK

    opened by harsh12312 0
  • The operation couldnā€™t be completed. (OSStatus error -10814.)

    The operation couldnā€™t be completed. (OSStatus error -10814.)

    If you are filing a bug report, please include information for the topics below. Also, please make sure to only report one bug/feature request/question per issue.

    Description

    I am getting The operation couldnā€™t be completed. (OSStatus error -10814.) upon trying to login. I suspect the setup around URI is wrong. It fails with web browser and iOS app.

    Versions

    iOS SDK version: 0.1.6 Spotify app version (if native SSO flow is involved): 8.5.66.762

    Severity

    Trivial

    Steps to Reproduce

    1. Add URI to Spotify dev dashboard myappmedia:// and myappmedia://callback
    2. Setup the URI Types in Xcode project with URL Schemes: myappmedia
    3. Add the following code to AppDelegate.swift:
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
            SpotifyLogin.shared.configure(clientID: "aaa123", clientSecret: "bbb123", redirectURL: URL(string: "myappmedia://callback")! ) 
            return true
        }
    

    , where "aaa123" and "bbb123" are real clientID and clientSecret respectively.

    1. Build and run, try to sign in with Facebook login
    2. Web page with the scope of permissions is presented
    3. Press AGREE

    Actual behaviour

    Get The operation couldnā€™t be completed. (OSStatus error -10814.) error after pressing Sign In button, and them after pressing AGREE nothing happens.

    Expected behaviour

    Successful sign in

    Logs

    2020-07-21 23:11:59.790846-0700 MyApp-iOS[70870:5832280] -canOpenURL: failed for URL: "spotify-action://authorize?utm_campaign=spotifylogin&show_dialog=true&nosignup=true&utm_medium=spotifylogin&scope=playlist-read-private%20playlist-read-collaborative%20playlist-modify-public%20playlist-modify-private&redirect_uri=myappmedia%3A%2F%2Fcallback&response_type=code&client_id= aaa123&nolinks=true&utm_source=spotify-sdk" - error: "The operation couldnā€™t be completed. (OSStatus error -10814.)"
    
    opened by evgeniyd 2
  • error returned in URL for AppDelegate callback

    error returned in URL for AppDelegate callback

    If you are filing a bug report, please include information for the topics below. Also, please make sure to only report one bug/feature request/question per issue.

    Description

    A concise description of what the problem is.

    Versions

    iOS SDK version Spotify app version (if native SSO flow is involved)

    Severity

    Trivial, Minor, Major, Catastrophic

    Steps to Reproduce

    1. Step by step instructions on how to reproduce this bug.
    2. The more detailed your list of instructions, the easier it is for the developer to track down the problem!

    Actual behaviour

    Describe what happens when you perform the steps above.

    Expected behaviour

    Describe what you expected to happen when performing the steps above.

    Logs

    Please include any relevant log output that might assist in tracking down the problem.

    when running the Sample test, for the following AppDelegate callback:

        func application(_ app: UIApplication,
                         open url: URL,
                         options: [UIApplicationOpenURLOptionsKey: Any] = [:]) -> Bool {
            let handled = SpotifyLogin.shared.applicationOpenURL(url) { _ in }
            return handled
        }
    

    I receive the following for the url content:

    loginsample://?error=invalid_app_identifier&error_description=The%20app%20identifier%20is%20not%20valid%20with%20the%20client%20ID%20provided

    This appears to be flagging an error regarding incorrect app id, though I have checked and rechecked and this is the ID as specified on the developer portal.

    Is this an issue? The Sample app ignores the contents returned in the url

    thanks.

    I am using the most recent Xcode Version 10.1 (10B61)

    opened by appsird 0
  • Verify Premium User

    Verify Premium User

    We have some properties like SPTUser and SPTProduct.premium to verify User premium account for Swift 2 Spotify Login framework.

    But, I am unable to find the way to verify the User is premium or not for Swift 4 SpotifyLogin framework.

    Please provide the solution for this asap.

    Thanks in Advance.

    opened by nagarajaghantasala 0
Releases(0.1.6)
Owner
Spotify
Spotify
Business-API - Business App an Application that show list business using the Yelp API

business-API Business App an Application that show list business using the Yelp

Edwin Niwarlangga 0 Jan 21, 2022
A framework that enhances HealthKit and the Fitbit API for iOS

VitoKit ?? Welcome to VitoKit... A framework that enhances HealthKit and the Fitbit API for iOS āœ… Features Wonderfully crafted animations Speedy setup

Vito 6 Nov 26, 2022
A Demo using Vision Framework building on Core ML Framework

Core-ML-Sample A Demo using Core ML, Vision Framework and Swift 4. This demo is based on Inception V3 network. You must run it with Xcode 9 and iOS 11

ęØ萧ēŽ‰ 215 Nov 9, 2022
RadioTimeKit - The Swift SDK for TuneIn RadioTimeKit is a Swift package to use the TuneIn API.

RadioTimeKit - The Swift SDK for TuneIn RadioTimeKit is a Swift package to use the TuneIn API. The goal for development was to have a Swift SDK to get

Frank Gregor 2 Jun 20, 2022
Swift SDK for Blockfrost.io API

Swift5 API client for Blockfrost Swift 5 SDK for Blockfrost.io API. Installation ā€¢ Usage ā€¢ API Endpoints Installation Swift package manager dependenci

blockfrost.io 10 Dec 24, 2022
āš”ļø A fully-featured and blazing-fast Swift API client to interact with Algolia.

The perfect starting point to integrate Algolia within your Swift project Documentation ā€¢ Community Forum ā€¢ Stack Overflow ā€¢ Report a bug ā€¢ FAQ ā€¢ Supp

Algolia 192 Dec 23, 2022
Simple proxy in Swift for converting between HTTP and API Gateway Lambda payloads

SwiftLambdaProxy A simple proxy that can convert HTTP requests to Lambda API Gat

Jānis KirŔteins 1 Jan 3, 2022
MpesaSDK - Swift SDK for the M-Pesa API (Mozambique)

M-Pesa SDK Swift package for M-Pesa API (Mozambique) Ready Methods/APIs C2B B2B

Algy Ali 16 Jul 29, 2022
Swiftcord - Swift wrapper for Discord's API. Maintained fork of Azoy's Sword

Swiftcord - A Discord Library for Swift Requirements macOS, Linux, iOS, watchOS,

Sketch 37 Nov 30, 2022
Unofficial Notion API SDK for iOS & macOS

NotionSwift Unofficial Notion SDK for iOS & macOS. This is still work in progress version, the module interface might change. API Documentation This l

Wojciech Chojnacki 59 Jan 8, 2023
150,000+ stickers API & SDK for iOS Apps.

English | ķ•œźµ­ģ–“ Stipop UI SDK for iOS Stipop SDK provides over 150,000 .png and .gif stickers that can be easily integrated into mobile app chats, comme

Stipop, Inc. 19 Dec 20, 2022
iOS SDK for the Box Content API

Box iOS SDK Getting Started Docs: https://developer.box.com/guides/mobile/ios/quick-start/ NOTE: The Box iOS SDK in Objective-C (prior to v3.0.0) has

Box 112 Dec 19, 2022
Sample iOS AR app using AR Quick Look API

ARQLSanta This is a minimal AR iOS app that uses the AR Quick Look API, displayi

Yasuhito Nagatomo 9 Aug 23, 2022
iOS SDK for access the OpenCage Geocoding API

OpenCageSDK Requirements OpenCageSDK works on iOS 9+ and requires ARC to build. It depends on the following Apple frameworks, which should already be

OpenCage GmbH 1 Jun 30, 2020
This project explores the capabilities of the new iOS 16+ Passkeys API to support password-less authentications.

iOS 16+ Passkeys Swift Sample This project explores the capabilities of the new iOS 16+ Passkeys API to support password-less authentications. āš ļø This

Hans Knƶchel 9 Dec 21, 2022
Open-source API Client for iOS, iPadOS, macOS. Built with SwiftUI

Yogu Open-source API Client for iOS, iPadOS, macOS. Built with SwiftUI ?? Yogu is currently in development, and not actually usable yet. Please DO NOT

Beomjun Gil 5 Oct 29, 2022
ResearchKit is an open source software framework that makes it easy to create apps for medical research or for other research projects.

ResearchKit Framework The ResearchKitā„¢ framework is an open source software framework that makes it easy to create apps for medical research or for ot

null 5.5k Dec 26, 2022
CareKit is an open source software framework for creating apps that help people better understand and manage their health.

CareKit CareKitā„¢ is an open source software framework for creating apps that help people better understand and manage their health. The framework prov

CareKit 2.3k Dec 27, 2022
Mapp SDK Inapp framework

Mapp SDK This repository contains the Mapp iOS SDK for in app messages. It is agreggation for Mapp SDK for push notifications. Integration Cocoa pods

Mapp 0 Dec 20, 2021