2017-07-28 214 views
0

我有这个功能来测试发送HTTP请求。Swift 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...") 
} 
+0

除了重复被迫展开,该代码应该是工作。其余的打印电话是否工作? –

回答

0

看来你没有正确使用闭包。试试这个:

// 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() 
0

看起来你需要在你的会话配置为使用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() 
相关问题