【问题标题】:Swift Http Client Doesn't Send RequestSwift Http 客户端不发送请求
【发布时间】:2017-07-28 19:05:01
【问题描述】:

我有这个功能来测试发送HTTP请求。

public func test(url: URL) {
    print("test")
    var request = URLRequest(url: url!)
    request.httpMethod = "GET"
    let session = URLSession.shared
    session.dataTask(with: request) { data, response, err in
        print("Entered the completionHandler")
        guard err == nil else {
            print("error calling GET")
            print(err!)
            return
        }
    }.resume()
}

我在测试中运行代码只是为了确保它正在发送请求。 而且它永远不会进入完成块(Entered the completionHandler 从未被打印出来)。我是 Swift 新手,我想念什么?

func test_download() {
    myClient.test(url: URL(string:"https://www.google.com")!)
    print("sleeping...")
    sleep(10)
    print("done...")
}

【问题讨论】:

  • 除了重复的强制展开之外,该代码应该可以工作。其余的打印调用是否正常工作?

标签: swift httprequest


【解决方案1】:

您似乎没有正确使用闭包。试试这个:

// No need to explicitly set GET method since this is the default one.
let session = URLSession.shared
var request = URLRequest(url: url!)
session.dataTask(with: request) { (data, response, err) in
    print("Entered the completionHandler")
    guard err == nil else {
        print("error calling GET")
        return
    }
    // Do whatever you need to with data and response in here

}.resume()

【讨论】:

    【解决方案2】:

    看起来您需要使用URLSessionConfiguration 对会话进行配置:-

    let urlConfig = URLSessionConfiguration.default
    urlConfig.timeoutIntervalForRequest = 5
    urlConfig.timeoutIntervalForResource = 5
    let session = Foundation.URLSession(configuration: urlConfig, delegate: nil, delegateQueue: nil)
    //Now try your code
    let task = session.dataTask(with: request) { data, response, err in
            print("Entered the completionHandler")
            guard err == nil else {
                print("error calling GET")
                print(err!)
                return
            }
        }
    task.resume()
    

    【讨论】:

      猜你喜欢
      • 2015-04-26
      • 1970-01-01
      • 2020-07-15
      • 1970-01-01
      • 1970-01-01
      • 2020-07-15
      • 2015-12-22
      • 2021-11-09
      • 2019-05-31
      相关资源
      最近更新 更多