无法发出将 tokenID 插入 request_token 字段的 POST 请求

Unable to make POST request that inserts tokenID into the request_token field

我一直收到同样的错误:

{"status_code":6,"status_message":"Invalid id: The pre-requisite id is invalid or not found."}

代码的重点是获取一个令牌 ID,然后使用该令牌 ID 创建一个会话 ID,但是每当我调用它时 returns 那个错误。

struct Post: Encodable {
    let requestToken: String

    enum CodingKeys: String, CodingKey {
        case requestToken = "request_token"
    }
}

struct Response: Codable {
    let success: Bool
    let sessionId: String

    enum CodingKeys: String, CodingKey {
        case success
        case sessionId = "session_id"
        }
    }

struct ResponseToken: Codable {
var success: Bool
var expires: String
var requestToken: String

enum CodingKeys: String, CodingKey {
    case success
    case expires = "expires_at"
    case requestToken = "request_token"
        }
    }

struct ErrorHandler: Codable {
    var status: String
    var statusCode: Int

    enum CodingKeys: String, CodingKey {
        case status = "status_message"
        case statusCode = "status_code"
    }
}


let apiKey = ""
let Testurl = URL(string: "https://api.themoviedb.org/3/authentication/session/new?api_key=\(apiKey)")!
let getToken = URL(string: "https://api.themoviedb.org/3/authentication/token/new?api_key=\(apiKey)")!
var sessionID = ""
var tokenID = ""

func taskPOSTRequest<RequestType: Encodable, ResponseType: Decodable>(url: URL, body: RequestType, response: ResponseType.Type, completionHandler: @escaping (ResponseType?, Error?) -> Void) {

       var request = URLRequest(url: url)
       request.httpMethod = "POST"
       request.addValue("application/json", forHTTPHeaderField: "Content-Type")
       request.httpBody =  try! JSONEncoder().encode(body)

       let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
           guard let data = data else {
               completionHandler(nil,error)
               return
           }
        print(String(data: data, encoding: .utf8)!)
           let decoder = JSONDecoder()

           do {
               let responseObject = try decoder.decode(ResponseType.self, from: data)
                   completionHandler(responseObject, nil)
           } catch {
                    completionHandler(nil, error)
        }
       }
       task.resume()
   }
func taskGETRequest<ResponseType: Decodable>(url: URL, response: ResponseType.Type, completionHandler: @escaping (ResponseType?, Error?) -> Void ){
let task = URLSession.shared.dataTask(with: url) { data, response, error in
        guard let data = data else {
            completionHandler(nil, error)
        return
    }
        let decoder = JSONDecoder()
        do {
            let responseObject = try decoder.decode(ResponseType.self, from: data)
                completionHandler(responseObject, nil)

        } catch {
            completionHandler(nil, error)
        }
    }
    task.resume()
}
taskGETRequest(url: getToken, response: ResponseToken.self) { (response, error) in
    if let response = response {
        tokenID = response.requestToken
        print(tokenID)
    } else {
        print(error!)
    }
}

taskPOSTRequest(url: Testurl, body: Post(requestToken: tokenID), response: Response.self) { (response, error) in
    if let response = response{
         sessionID = response.sessionId
           print(sessionID)
    } else {
        print(error!)
    }
}

我一直收到同样的错误:

{"status_code":6,"status_message":"Invalid id: The pre-requisite id is invalid or not found."}

因为两个请求是相互依赖的,都是异步的。

在您的示例中,API API B 的请求需要 A 的响应。所以下面应该可以解决问题.. 我们等待第一个请求完成,一旦我们有了令牌,我们就会发出第二个请求。

所以getToken API会生成一个token,然后使用token创建session。 :)

taskGETRequest(url: getToken, response: ResponseToken.self) { (response, error) in
    if let response = response {
        tokenID = response.requestToken
        print(tokenID)

        taskPOSTRequest(url: Testurl, body: Post(requestToken: tokenID), response: Response.self) { (response, error) in
            if let response = response{
                sessionID = response.sessionId
                print(sessionID)
            } else {
                print(error!)
            }
        }

    } else {
        print(error!)
    }
}