swift - 如何将 Spotify token 添加到搜索艺术家的轨道

标签 swift alamofire spotify

尝试通过 spotify web api 搜索艺术家的轨道。然而 Spotify 已经更新了它的 api,现在需要一个 Token 来访问它。我不得不承认,但找不到任何关于如何通过 Alamofire 使用它的信息。这是代码。任何帮助将不胜感激,或者被指出正确的方向。

class TableViewController: UITableViewController {

    var names = [String]()

    var searchURL = "https://api.spotify.com/v1/search?q=Odesza&type=track"

    typealias JSONStandard = [String : AnyObject]

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        callAlamo(url: searchURL)
    }

    func callAlamo(url : String){
        AF.request(url).responseJSON(completionHandler: {
            response in
            self.parseData(JSONData: response.data!)
        })

    }
    func parseData(JSONData : Data) {
        do {
            var readableJSON = try JSONSerialization.jsonObject(with: JSONData, options: .mutableContainers) as! JSONStandard
        print(readableJSON)
            if let tracks = readableJSON["tracks"] as? JSONStandard{
               // print(readableJSON)

                if let items = tracks["items"] as? NSArray{

                    for i in 0..<items.count{
                        let item = items[i] as! JSONStandard

                        let name = item["name"] as! String
                        names.append(name)

                        self.tableView.reloadData()

                    }
                }
            }
        }
        catch{
            print(error)
        }
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return names.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")
       cell?.textLabel?.text = names[indexPath.row]
        return cell!
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

最佳答案

您可以像这样在 header 中设置访问 token 。有关详细信息和示例,您可以查看offical reference .顺便说一下 this question 的可能重复项

   let headers = [
    "Authorization": "Bearer {your access token}"
]

AF.request(.GET, searchURL, headers: headers)
         .responseJSON { response in
             debugPrint(response)
         }

关于swift - 如何将 Spotify token 添加到搜索艺术家的轨道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54623982/

相关文章:

ios - ReactiveCocoa 问题

ios - Firebase iOS SDK - 如何计算表现良好的 child 数量?

ios - CoreMIDI Thru Connection 是如何在 swift 4.2 中创建的?

javascript - Spotify API - 创建临时播放列表

google-analytics - 在Spotify-App中用于分析跟踪的网站URL?

ios - 无法关闭 Swift 中的导航 Controller

下载 Alamofire 后快速保存文件

ios - Alamofire 后台服务,全局经理?全局授权 header ?

Swift 3 和 Alamofire send 方法作为参数

spotify - 从 Spotify 应用程序内访问 Spotify 元数据 API?