【问题标题】:URLSession does not run second GETURLSession 不运行第二个 GET
【发布时间】:2019-10-08 19:10:48
【问题描述】:

我无法完成第二个“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”只是为了尝试,但它也不起作用。

谁能给我点灯?

问候

【问题讨论】:

    标签: swift get urlsession


    【解决方案1】:

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

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

    【讨论】:

    • 我刚试了一下,效果很好我对“completion”和“@escaping”一无所知,这很有趣!谢谢;)
    • 最简单的方法是链接两个方法。致电GetSerieID,当您找到SerielID 时,请致电GetSerieData。这应该有效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多