将 Bearer Token 添加到 Swift 中的 header 时出现问题(HTTP POST 调用)

Problem with adding Bearer Token to header in Swift (HTTP POST call)

我正在尝试对 API 进行 HTTP POST 调用。

我在 Postman 中输入了这些确切的参数并取回了数据。这段代码似乎有问题。我敢打赌,问题出在没有正确添加令牌,因为我之前使用类似的代码成功进行了 POST 调用,但没有令牌。

       let parameters = ["ne_lat": "52.6", "ne_lng": "13.5", "sw_lat": "52.4", "sw_lng": "13.3", "user_latitude": "52.5311", "user_longitude": "13.3849", "zoom": "16"]

        //create the url with URL
        let url = URL(string: "https://web-production.lime.bike/api/rider/v1/views/map")! //change the url

        //create the session object
        let session = URLSession.shared

        //now create the URLRequest object using the url object
        var request = URLRequest(url: url)
        request.httpMethod = "GET" //set http method as GET

        do {
            request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // pass dictionary to nsdata object and set it as request body
        } catch let error {
            print(error.localizedDescription)
        }

        request.addValue("Bearer eyJ0eXAiOiJKdbnwjnOiJIUzI1NiJ9.eyJ1c2VyX3Rva2VuIjoiVjZFUHSBDRVJEMyIsImxvZ2luX2NvdW50Ijo1fQ.5YP4tcLSAINDoR-txdDsYCh_k_5aRt4cIu8DvTa00GU", forHTTPHeaderField: "authorization")

        //create dataTask using the session object to send data to the server
        let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in

            guard error == nil else {
                return
            }

            guard let data = data else {
                return
            }

            do {
                //create json object from data
                if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
                    print(json)
                    // handle json...
                }
            } catch let error {
                print(error.localizedDescription)
            }
        })
        task.resume()

API documentation for this call

Link 到文档:https://github.com/ubahnverleih/WoBike/blob/master/Lime.md

我在处理 Alamofire 令牌时遇到了类似的问题,我用 String concat 解决了。

试试这个:

 request.addValue("{\"token\":\" eyJ0eXAiOiJKdbnwjnOiJIUzI1NiJ9.eyJ1c2VyX3Rva2VuIjoiVjZFUHSBDRVJEMyIsImxvZ2luX2NvdW50Ijo1fQ.5YP4tcLSAINDoR-txdDsYCh_k_5aRt4cIu8DvTa00GU\"}", forHTTPHeaderField: "authorization")