gpt4 book ai didi

ios - URLSession dataTask completionHandler 在 Playground 上不起作用

转载 作者:搜寻专家 更新时间:2023-11-01 05:47:19 25 4
gpt4 key购买 nike

我从 youtube 上观看了一个教程并尝试了该教程。然后我写 Playground 文件中的代码,我没有得到任何结果,但没有错误。因此,我在 XCode 中创建了一个新项目。然后向 Main.StoryBoard 添加一个 Button 并将 UI 连接到代码。完成所有必要的事情后,我在模拟器中运行项目,一切顺利,我可以看到完成处理程序中的所有工作。以下是 XCode 项目中的代码。

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

以下是 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()

最佳答案

您需要告诉 playground 继续执行足够长的时间以使您的异步代码完成。为此:

import PlaygroundSupport 

PlaygroundPage.current.needsIndefiniteExecution = true

来自 Apple's docs on this property :

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.

关于ios - URLSession dataTask completionHandler 在 Playground 上不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48633620/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com