URLSession dataTask completionHandler在游乐场中不起作用
我在youtube上观看了一个教程并尝试了这些教程。然后我在操场文件中写了
代码,但没有结果,但没有错误。
因此我在XCode中创建了一个新项目。然后向Main.StoryBoard添加一个Button并将UI连接到代码。在完成所有必要的事情后,我在模拟器中运行项目,一切顺利,我可以看到完成处理程序内的所有工作。以下是XCode项目中的代码。
I watched a tutorial from youtube and tried that tutorials. Then I write the code in playground file and I got no result but there is no error. Thus I make a new Project in XCode. Then add a Button to Main.StoryBoard and connect the UI to code. After doing all necessary things I runthe project in simulator and everything go well and I can see all the work inside completion handler. Following is the code in XCode project.
@IBAction func doNetwork(_ sender: UIButton) {
print("start network jobs...")
// url
let url: URL! = URL(string: "http://192.168.0.12/swnet.php")
URLCache.shared = URLCache(memoryCapacity: 0, diskCapacity: 0, diskPath: nil)
// url session
let session = URLSession.shared
let task: URLSessionDataTask = session.dataTask(with: url, completionHandler: {
(data, response, error) in
print("Handler")
if let respData = data {
print("Data")
print(respData)
}
if let resp = response {
print("Resp")
print(resp)
}
if let err = error {
print("Error")
print(err)
}
})
task.resume()
}
以下是操场上的代码。
Following is the code in playground.
// url
let url: URL! = URL(string: "http://192.168.0.12/swnet.php")
URLCache.shared = URLCache(memoryCapacity: 0, diskCapacity: 0, diskPath: nil)
// url session
let session = URLSession.shared
let task: URLSessionDataTask = session.dataTask(with: url, completionHandler: {
(data, response, error) in
print("Handler")
if let respData = data {
print("Data")
print(respData)
}
if let resp = response {
print("Resp")
print(resp)
}
if let err = error {
print("Error")
print(err)
}
})
task.resume()
您需要告诉操场继续执行足够长的时间以完成异步代码。为此:
You need to tell the playground to continue execution long enough for your async code to complete. To do that:
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
来自 Apple关于此属性的文档:
默认情况下,执行所有顶级代码,然后执行
终止。使用异步代码时,启用无限
执行以允许在
playground的顶级代码结束后继续执行。反过来,这给线程
和回调时间执行。
By default, all top-level code is executed, and then execution is terminated. When working with asynchronous code, enable indefinite execution to allow execution to continue after the end of the playground’s top-level code is reached. This, in turn, gives threads and callbacks time to execute.