URLSession 没有 运行 秒 GET

URLSession does not run second GET

我无法执行第二个 "GET" 任务。

这是新手打架学习Swift。

我正在使用 "thetvdb" API 获取系列信息和枚举。
API 信息:https://api.thetvdb.com/swagger

第一步是登录并获取带有 "POST" 到 https://api.thetvdb.com/login 的令牌。

接下来是"GET"想要的系列的ID,下一个函数:

    func GetSerieID(theSerieName: String){

        refreshToken() //Refresh the token before anything

        let theURL = "https://api.thetvdb.com/search/series?name=" + theSerieName
        let url = URL(string: theURL.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)!

        var request = URLRequest(url: url)
        request.httpMethod = "GET"
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")
        request.setValue( "Bearer \(token)", forHTTPHeaderField: "Authorization") // the refreshed token

        let task = URLSession.shared.dataTask(with: request) { (data, response, error) in

            if let data = data{
                // I use SwiftyJSON.swift to manage the JSON's
                let json = try? JSON(data: data)
                theJSONContent = json!["data"]

                // Manage the theJSONContent to get the ID

            }

            if let httpResponse = response as? HTTPURLResponse {
                print("httpResponse: " + String(httpResponse.statusCode) + " >>GetSerieID\n")
            }
        }
        task.resume()
    }

GetSerieID 函数工作异常,但下一个 GetSerieData 函数没有建立 URLSession,它立即跳转到 return!

    func GetSerieData(theSerieID: String) -> JSON {

        refreshToken() //Refresh the token before anything

        var theJSONContent = JSON()

        let theURL = "https://api.thetvdb.com/series/" + theSerieID + "/episodes"
        let url = URL(string: theURL.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)!

        var request = URLRequest(url: url)
        request.httpMethod = "GET"
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")
        request.setValue( "Bearer \(token)", forHTTPHeaderField: "Authorization") // the refreshed token

        let task = URLSession.shared.dataTask(with: request) { (data, response, error) in

            if let data = data{
                // I use SwiftyJSON.swift to manage the JSON's
                let json = try? JSON(data: data)
                theJSONContent = json!["data"]

            }

            if let httpResponse = response as? HTTPURLResponse {
                print("httpResponse: " + String(httpResponse.statusCode) + " >>GetSerieID\n")
            }
        }
        task.resume()

        return theJSONContent
    }

接下来是请求:

Printing description of request:
▿ https://api.thetvdb.com/series/300472/episodes
  ▿ url : Optional<URL>
    ▿ some : https://api.thetvdb.com/series/300472/episodes
  - cachePolicy : 0
  - timeoutInterval : 60.0
  - mainDocumentURL : nil
  - networkServiceType : __ObjC.NSURLRequest.NetworkServiceType
  - allowsCellularAccess : true
  ▿ httpMethod : Optional<String>
    - some : "GET"
  ▿ allHTTPHeaderFields : Optional<Dictionary<String, String>>
    ▿ some : 3 elements
      ▿ 0 : 2 elements
        - key : "Accept"
        - value : "application/json"
      ▿ 1 : 2 elements
        - key : "Content-Type"
        - value : "application/json"
      ▿ 2 : 2 elements
        - key : "Authorization"
        - value : "Bearer eyJhbGciOiJSUzI1NiIsInR5tokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentoken"
  - httpBody : nil
  - httpBodyStream : nil
  - httpShouldHandleCookies : true
  - httpShouldUsePipelining : false

"GET" 的两个函数实际上是相同的,只是 URL 发生了变化。 这当然很简单,但我被卡住了。

如果我将它们翻转并先调用 GetSerieData,然后调用 GetSerieID,那么第一个再次起作用,但第二个不起作用。

很明显,这是通过与 GET 建立第一个连接的问题,它不会结束会话或其他东西,但我找不到如何处理它。 在某些版本的代码中,我添加了一个 "DELETE" 只是为了尝试,但它也不起作用。

有人可以给我一些灯吗?

此致

因为这个任务是异步的,而且是立即返回。您需要添加完成块。

func GetSerieData(theSerieID: String, completion: @escaping (JSON) -> Void) {

        refreshToken() //Refresh the token before anything

        var theJSONContent = JSON()

        let theURL = "https://api.thetvdb.com/series/" + theSerieID + "/episodes"
        let url = URL(string: theURL.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)!

        var request = URLRequest(url: url)
        request.httpMethod = "GET"
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")
        request.setValue( "Bearer \(token)", forHTTPHeaderField: "Authorization") // the refreshed token

        let task = URLSession.shared.dataTask(with: request) { (data, response, error) in

            if let data = data{
                // I use SwiftyJSON.swift to manage the JSON's
                let json = try? JSON(data: data)
                theJSONContent = json!["data"]
                completion(theJSONContent)
            }

            if let httpResponse = response as? HTTPURLResponse {
                print("httpResponse: " + String(httpResponse.statusCode) + " >>GetSerieID\n")
            }
        }
        task.resume()
    }