SpotifyLogin is a Swift 5 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
A simple to use, standard interface for authenticating to oauth 2.0 protected endpoints via SFSafariViewController.

AuthenticationViewController A simple to use, standard interface for authenticating to OAuth 2.0 protected endpoints via SFSafariViewController. Instr

Raul Riera 256 Dec 14, 2022
OAuth2 framework for macOS and iOS, written in Swift.

OAuth2 OAuth2 frameworks for macOS, iOS and tvOS written in Swift 5.0. ⤵️ Installation ?? Usage ?? Sample macOS app (with data loader examples) ?? Tec

Pascal Pfiffner 1.1k Jan 2, 2023
Declarative Swift framework for Attributed Role-based Access Control management

Koosa Declarative Swift framework for Attributed Role-based Access Control management Check out this blog post for full explanation and more details:

Mostafa Abdellateef 37 Oct 24, 2022
A simple project for Face ID Authentication for iOS device using LocalAuthentication Framework

BiometricAuthentication This respository is a simple project for Face ID Authentication for iOS device using LocalAuthentication Framework and infoPli

Lee McCormick 0 Oct 23, 2021
Easy to use OAuth 2 library for iOS, written in Swift.

Heimdallr Heimdallr is an OAuth 2.0 client specifically designed for easy usage. It currently supports the resource owner password credentials grant f

trivago N.V. 628 Oct 17, 2022
Swift based OAuth library for iOS

OAuthSwift Swift based OAuth library for iOS and macOS. Support OAuth1.0, OAuth2.0 Twitter, Flickr, Github, Instagram, Foursquare, Fitbit, Withings, L

OAuthSwift 3.1k Jan 3, 2023
A swift implementation of OAuth2

#AlamofireOauth2 A Swift implementation of OAuth2 for iOS using Alamofire. #Intro This library is heavilly inspired by the SwiftOAuth2 repository from

Edwin Vermeer 83 Dec 5, 2022
FCLAuthSwift is a Swift library for the Flow Client Library (FCL) that enables Flow wallet authentication on iOS devices.

FCLAuthSwift is a Swift library for the Flow Client Library (FCL) that enables Flow wallet authentication on iOS devices. Demo The demo a

Zed 3 May 2, 2022
SFA: Swift Firebase Auth Project✨

SFAssets SFA: Swift Firebase Auth Project✨ 파이어베이스로 로그인/회원가입 뿌수기 Login View (로그인 뷰) 담당 기능 배정 Facebook Login 후릐 Google Login 태끼 Apple Login 이준초이 Github

null 6 Nov 7, 2021
An poc to make a login using Auth0 in Swift

Swift-Auth0-poc This app is an poc to make a login using Auth0. If you want to try it yourself here is a small tutorial on how to do it. 1. Configure

Sem de Wilde 1 Jan 21, 2022
Swift async/await OAuth 2.0 HTTP request library.

SwAuth SwAuth is an OAuth 2.0 HTTP request library written in Swift iOS 15.0+, macOS 12.0+, watchOS 8.0+, and tvOS 15.0+. Features Requirements Instal

Colaski 17 Nov 5, 2022
Swift based OAuth library for iOS and macOS

OAuthSwift Swift based OAuth library for iOS and macOS. Support OAuth1.0, OAuth2.0 Twitter, Flickr, Github, Instagram, Foursquare, Fitbit, Withings, L

OAuthSwift 3.1k Jan 3, 2023
Swift framework for authenticating with the Spotify API

SpotifyLogin SpotifyLogin is a Swift 5 Framework for authenticating with the Spotify API. Usage of this framework is bound under the Developer Terms o

Spotify 344 Jan 4, 2023
An iOS app that visually clones Spotify's app and consumes the official Spotify's Web API to show(and play) songs, podcasts, artists and more.

SpotifyClone An iOS app that visually clones Spotify's app and consumes the official Spotify's Web API to show(and play) songs, podcasts, artists and

null 104 Jan 7, 2023
An iOS app that visually clones Spotify's app and consumes the official Spotify's Web API to show(and play) songs, podcasts, artists and more.

SpotifyClone An iOS app that visually clones Spotify's app and consumes the official Spotify's Web API to show(and play) songs, podcasts, artists and

Gabriel Denoni 11 Dec 27, 2021
A simple library to make authenticating tvOS apps easy via their iOS counterparts.

Voucher The new Apple TV is amazing but the keyboard input leaves a lot to be desired. Instead of making your users type credentials into their TV, yo

Riz 516 Nov 24, 2022
A simple library to make authenticating tvOS apps easy via their iOS counterparts.

Voucher The new Apple TV is amazing but the keyboard input leaves a lot to be desired. Instead of making your users type credentials into their TV, yo

Riz 516 Nov 24, 2022
A simple to use, standard interface for authenticating to oauth 2.0 protected endpoints via SFSafariViewController.

AuthenticationViewController A simple to use, standard interface for authenticating to OAuth 2.0 protected endpoints via SFSafariViewController. Instr

Raul Riera 256 Dec 14, 2022
AnylineFaceAuthentication pairs identity document scanning with a real-time liveness check utilizing the iPhone's camera, best suited for authenticating users over the internet.

AnylineFaceAuthentication AnylineFaceAuthentication pairs identity document scanning with a real-time liveness check utilizing the iPhone's camera, be

null 0 Mar 7, 2022
An Elegant Spotify Web API Library Written in Swift for iOS and macOS

Written in Swift 4.2 Spartan is a lightweight, elegant, and easy to use Spotify Web API wrapper library for iOS and macOS written in Swift 3. Under th

Dalton Hinterscher 107 Nov 8, 2022