首页 > 解决方案 > URLSession 不运行第二个 GET

问题描述

我无法让我的第二个“GET”任务工作。

这是学习 Swift 的初学者之战。

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

第一步是登录并通过“POST”获取令牌到https://api.thetvdb.com/login

接下来是使用下一个函数“获取”所需系列的 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,它立即跳转到返回!

    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”只是为了尝试,但它也不起作用。

有人可以给我一些光吗?

问候

标签: swiftgeturlsession

解决方案


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

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()
    }


推荐阅读