ios怎么用spotify

Authenticating through an API like Spotify in order to access and modify a user’s information, music, follows, and so on can be so confusing especially for beginners. Why you may ask? If you have little to no knowledge about dealing with headers, SDK, web APIs, tweaking Xcode’s Build Settings and Info.plist then you are in the right place. My goal in this article is to improve Spotify’s Authorization Guide with better visuals, clearer step by step, actual Swift codes, and more importantly, have my readers level up.

通过诸如Spotify之类的API进行身份验证以访问和修改用户的信息,音乐,跟随等内容可能会造成混乱,尤其是对于初学者而言。 你为什么会问? 如果您几乎不了解处理标头,SDK,Web API,调整Xcode的Build Settings和Info.plist,那么您来对地方了。 本文的目的是通过更好的视觉效果,更清晰的逐步操作,实际的Swift代码,以及更重要的是提高读者的水平来改进Spotify的授权指南。

我们去取得它 (Let’s get it)

I will go over refreshable authorization and authentication process in Swift using Spotify’s iOS SDK. This is a task all software engineers should be comfortable with especially for a very secure backend like Spotify.

我将使用Spotify的iOS SDK讨论Swift中可刷新的授权和身份验证过程。 这是所有软件工程师都应该适应的任务,尤其是对于像Spotify这样的非常安全的后端。

准备环境 (Prepare Your Environment)

I will assume that you registered your app and have a client Identifier from Spotify’s Developer Dashboard. If not, read through Spotify’s iOS SDK Quick Start and App Settings guide. It is important to have appName:// whitelisted as a redirect URIs in your project in Spotify Dashboard in order for Spotify to know how to go back to your app.

我将假设您已经注册了应用程序,并且具有Spotify开发人员仪表板中的客户端标识符。 如果没有,请仔细阅读Spotify的iOS SDK快速入门和应用设置指南。 重要的是,在Spotify信息中心的项目中将appName://作为重定向URI列入白名单,以便Spotify知道如何返回到您的应用程序。

在Xcode中设置Spotify的iOS SDK (Setup Spotify’s iOS SDK in Xcode)

Skip this section if you are not planning to use Spotify’s iOS SDK. If you want to make your user’s experience as delightful as possible, download the iOS SDK from GitHub and add it to your Xcode project.

如果您不打算使用Spotify的iOS SDK,请跳过本节。 如果您想使用户的体验尽可能愉悦,请从GitHub下载iOS SDK ,并将其添加到您的Xcode项目中。

Create a new file, header file, and name it like so AppName-Bridging-Header. Then replace all its contents with#import <SpotifyiOS/SpotifyiOS.h>. Your project navigator should look like the image below. Do not worry about the GoogleService-Info.plist file unless you have pods installed.

创建一个新文件,头文件,并命名为AppName-Bridging-Header 。 然后将其所有内容替换为#import <SpotifyiOS/SpotifyiOS.h> 。 您的项目导航器应如下图所示。 除非您已安装Pod,否则不必担心GoogleService-Info.plist文件。

设置-ObjC链接器标志 (Set -ObjC Linker Flag)

In order to support the iOS SDK and compile the Objective-C code contained inside the iOS SDK, we will need to add -Objc linker flag. In Xcode, add the linker flag like the image below.

为了支持iOS SDK并编译iOS SDK中包含的Objective-C代码,我们需要添加-Objc链接器标志。 在Xcode中,添加链接器标志,如下图所示。

添加桥接标题 (Add Bridging Header)

Then we need to add a bridging header next that will allow us to include Objective-C binaries inside our Swift app. We can do that by searching Objective-C Bridging Header in Build Settings and settings its value the same as the name of our header file like the image below

然后,我们需要添加一个桥接标头,该标头将使我们能够在Swift应用程序中包含Objective-C二进制文件。 我们可以通过在“构建设置”中搜索“ Objective-C桥接头”并将其值设置为与我们的头文件的名称相同的方式来做到这一点,如下图所示

确认信息(Confirm Info)

You will also need to add a new URL Types in Info tab. Give the identifier as your Bundle Id, and the value as your callback without the :// like the image below.

您还需要在“信息”选项卡中添加新的URL类型。 给出标识符作为您的Bundle ID,并给值作为不带://回调, ://图所示。

Lastly for security purposes, you will need to open Info.plist as source code and make sure you tell NSAppTransportSecurity that you are supporting the domain, spotify.com. Take this time to also make sure that you have the same changes on your Info.plist as mine that are marked with blue horizontal lines.

最后,出于安全性考虑,您需要打开Info.plist作为源代码,并确保告知NSAppTransportSecurity您正在支持域Spotify.com。 请花一些时间确保在Info.plist上所做的更改与用蓝色水平线标记的更改相同。

授权流程 (Authorization Flows)

Spotify comes with four flows to obtain app authorization. Those are:

Spotify附带四个流程来获取应用程序授权。 那些是:

  • Refreshable user authorization: Authorization Code Flow

    可刷新的用户授权:授权码流程

  • Refreshable user authorization: Authorization Code Flow With Proof Key for Code Exchange (PKCE)

    可刷新的用户授权:具有用于代码交换(PKCE)的证明密钥的授权代码流

  • Temporary user authorization: Implicit Grant

    临时用户授权:隐式授予

  • Refreshable app authorization: Client Credentials Flow

    可刷新的应用授权:客户端凭据流

In this article, we will be following the second option, Authorization Code Flow With Proof Key for Code Exchange (PKCE). According to Spotify, authorization code flow with PKCE is the best option for mobile and desktop applications because it is unsafe to store client secret. It also provides your app with an access token that can be refreshed.

在本文中,我们将采用第二种选择,即带有代码交换证明密钥的授权代码流(PKCE) 。 根据Spotify的说法,带有PKCE的授权码流是移动和桌面应用程序的最佳选择,因为它不安全地存储客户端机密。 它还为您的应用程序提供了可以刷新的访问令牌。

编码时间 (Time to Code)

It’s time to finally code. My code mostly came from one of Spotify’s iOS SDK Demo Projects, SPTLoginSampleAppSwift.

现在是时候开始编写代码了。 我的代码主要来自Spotify的iOS SDK演示项目之一SPTLoginSampleAppSwift 。

From Authorization Code Flow With Proof Key for Code Exchange (PKCE) it is telling us to 1. Create the code verifier challenge then 2. Construct the authorization URI. Fortunately for us, since we are using the Spotify iOS SDK, we can complete those two steps by initiating a session with our session manager. Simply call the following method on button tap.

带有代码交换证明密钥(PKCE)的授权代码流中,我们告诉我们1.创建代码验证者质询,然后2.构造授权URI 。 对我们来说幸运的是,由于我们使用的是Spotify iOS SDK,因此可以通过与会话管理器启动会话来完成这两个步骤。 只需在按钮点击上调用以下方法。

  @objc func didTapConnect(_ button: UIButton) {    guard let sessionManager = sessionManager else { return }    if #available(iOS 11, *) {      // Use this on iOS 11 and above to take advantage of SFAuthenticationSession      sessionManager.initiateSession(with: scopes, options: .clientOnly)    } else {      // Use this on iOS versions < 11 to use SFSafariViewController      sessionManager.initiateSession(with: scopes, options: .clientOnly, presenting: self)    }  }

The next step is 3. Your app redirects the user to the authorization URI. After initiating a session with session manager, our Spotify app will be launched to get permissions specified in scopes. If user accepts, we will get the code we need to get our access token.

下一步是3。您的应用将用户重定向到授权URI 。 与会话管理器启动会话后,将启动我们的Spotify应用以获取在范围中指定的权限。 如果用户接受,我们将获得获取访问令牌所需的code

The last thing we need to do is 4. Exchange the authorization code for an access token. To do that we will need to make a POST request to https://accounts.spotify.com/api/token endpoint with the following body (client_id, grant_type, code, redirect_uri) filled out.

我们需要做的最后一件事是4.交换访问令牌的授权代码。 为此,我们需要向https://accounts.spotify.com/api/token端点发出POST请求,并填写以下正文(client_id,grant_type,代码,redirect_uri)。

///fetch Spotify access token. Use after getting responseTypeCode  func fetchSpotifyToken(completion: @escaping ([String: Any]?, Error?) -> Void) {    let url = URL(string: "https://accounts.spotify.com/api/token")!    var request = URLRequest(url: url)    request.httpMethod = "POST"    let spotifyAuthKey = "Basic \((spotifyClientId + ":" + spotifyClientSecretKey).data(using: .utf8)!.base64EncodedString())"    request.allHTTPHeaderFields = ["Authorization": spotifyAuthKey, "Content-Type": "application/x-www-form-urlencoded"]    do {      var requestBodyComponents = URLComponents()      let scopeAsString = stringScopes.joined(separator: " ") //put array to string separated by whitespace      requestBodyComponents.queryItems = [URLQueryItem(name: "client_id", value: spotifyClientId), URLQueryItem(name: "grant_type", value: "authorization_code"), URLQueryItem(name: "code", value: responseTypeCode!), URLQueryItem(name: "redirect_uri", value: redirectUri.absoluteString), URLQueryItem(name: "code_verifier", value: codeVerifier), URLQueryItem(name: "scope", value: scopeAsString),]      request.httpBody = requestBodyComponents.query?.data(using: .utf8)      let task = URLSession.shared.dataTask(with: request) { data, response, error in        guard let data = data,                            // is there data        let response = response as? HTTPURLResponse,  // is there HTTP response        (200 ..< 300) ~= response.statusCode,         // is statusCode 2XX        error == nil else {                           // was there no error, otherwise ...          print("Error fetching token \(error?.localizedDescription ?? "")")          return completion(nil, error)        }        let responseObject = try? JSONSerialization.jsonObject(with: data) as? [String: Any]        print("Access Token Dictionary=", responseObject ?? "")        completion(responseObject, nil)      }      task.resume()    } catch {      print("Error JSON serialization \(error.localizedDescription)")    }  }

According to the guide, the exchange requires code_verifier to be included in the body, however, at the time of this writing, it is not required since we are using the iOS SDK. It may be required for web API authorization and authentication flow.

根据指南,交换要求将code_verifier包含在主体中,但是在撰写本文时,由于我们使用的是iOS SDK,因此不需要。 Web API授权和身份验证流程可能需要它。

ViewController.swift before authenticating, playing current music, pause current music.
进行身份验证,播放当前音乐,暂停当前音乐之前的ViewController.swift。

而已! (That’s it!)

Congratulations on successfully doing an authorization and authenticating using Spotify iOS SDK. You have leveled up in iOS development

ios怎么用spotify_在iOS中通过Spotify进行身份验证相关推荐

  1. 如何使用Google Authenticator在ASP.NET Core中设置两因素身份验证

    介绍 (Introduction) In this article, we are going to learn how to perform two-factor authentication in ...

  2. ASP.NET的MVC中使用Cookie做身份验证(附代码下载)

    场景 ASP.NET的MVC中使用Session做身份验证(附代码下载): https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/1071 ...

  3. 如何使用Java和XML Config在Spring Security中启用HTTP基本身份验证

    在上一篇文章中,我向您展示了如何在Java应用程序中启用Spring安全性 ,今天我们将讨论如何使用Spring Security 在Java Web应用程序中启用Basic HTTP身份验证 . 如 ...

  4. 在SPA应用中利用JWT进行身份验证

    版权声明:本文为博主chszs的原创文章,未经博主允许不得转载. https://blog.csdn.net/chszs/article/details/79639919 在SPA应用中利用JWT进行 ...

  5. aws rds监控慢sql_AWS RDS SQL Server中的初始Windows身份验证配置

    aws rds监控慢sql In this article, we will be exploring the process of enabling Windows authentication i ...

  6. aws rds监控慢sql_AWS RDS SQL Server中的高级Windows身份验证配置

    aws rds监控慢sql This article will cover advanced configurations for Windows Authentication in AWS RDS ...

  7. C#中连接使用Windows身份验证的sql server数据库

    C#中连接使用Windows身份验证的sql server数据库 最近在写一个系统,主要使用C#语言完成系统内各功能模块的编写.系统包含数据库,需要对数据库内的数据进行增删改查,这就涉及到了数据库的连 ...

  8. ASP.NET的MVC中使用Session做身份验证(附代码下载)

    场景 ASP.NET中MVC编程模式简介与搭建HelloWorld项目: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/10679 ...

  9. app engine_App Engine中的Google Services身份验证,第2部分

    app engine 在本教程的第一部分中, 我介绍了如何使用OAuth进行Google API服务的访问/身份验证. 不幸的是,正如我稍后发现的那样,我使用的方法是OAuth 1.0,显然现在Goo ...

最新文章

  1. linux下php连接mysql数据库_Linux下PHP连接Oracle数据库
  2. jQuery Lightbox图片放大预览
  3. php滚动到指定位置,JQuery插件:ScrollTo平滑滚动到页面指定位置
  4. mysql ip v4 v6_mysql IPv4 IPv6
  5. 感恩节(美食火鸡大餐)PNG免扣素材 总有一款你用得上
  6. 在Anaconda上安装Caffe 和 CUDA
  7. 2021/4/2听宫老师演讲有感。
  8. RHadoop的技术性文章
  9. C语言程序100例之C#版-029
  10. 二阶有源低通滤波器设计
  11. weblogic安装部署升级小结
  12. IOI2021 国家集训队作业部分题解
  13. 用串口操作手机收发短信总结
  14. layui后台首页关闭标签
  15. 【车间调度】免疫遗传算法求解多目标生产调度问题【含Matlab源码 710期】
  16. 自动驾驶专题介绍 ———— 超声波雷达
  17. 工控 组态王6.60 SP3软件7.5 SP4 授权软件狗 USB 硬件狗 分享 下载
  18. goLang 位左移
  19. 输出2+22+222+2222类型问题(笔记)
  20. R语言_R中的帮助函数

热门文章

  1. 如何安全地嵌入第三方js – FBML/caja/sandbox/ADsafe简介
  2. 运维老兵对运维中常见技术类问题剖析
  3. java gc 时间_Java GC日志查看,GC日志时间分析
  4. iOS 贪吃蛇单机版的实现
  5. Google Summer of Code 2017 开放报名;交互式线上科学期刊 Distill 上线等 | AI 研习社周刊...
  6. Mongo与robomongo
  7. carbondata与mysql_carbondata使用总结
  8. 考研概率论与数理统计
  9. uni-app封装请求方法与api封装调用
  10. 基于PHP+MySQL简历模板下载管理系统