许多Cocoa和CocoaTouch方法在Objective-C中将完成回调实现为块,在Swift中将闭包实现为闭包。但是,当在Playground中尝试这些时,从不调用完成。例如:
// Playground - noun: a place where people can play
import Cocoa
import XCPlayground
let url = NSURL(string: "http://stackoverflow.com")
let request = NSURLRequest(URL: url)
NSURLConnection.sendAsynchronousRequest(request, queue:NSOperationQueue.currentQueue() {
response, maybeData, error in
// This block never gets called?
if let data = maybeData {
let contents = NSString(data:data, encoding:NSUTF8StringEncoding)
println(contents)
} else {
println(error.localizedDescription)
}
}
我可以在我的游乐场时间线中看到控制台输出,但我的完成块中的println
从未被调用过……
发布于 2014-06-06 01:17:36
虽然您可以手动运行运行循环(或者,对于不需要运行循环的异步代码,可以使用其他等待方法,如分派信号量),但我们在游乐场中提供的等待异步工作的“内置”方法是导入XCPlayground
框架并设置XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
。如果设置了此属性,当顶级游乐场源代码完成时,我们将继续旋转主运行循环,以便异步代码有机会运行,而不是停止游乐场。我们最终将在超时后终止游乐场,该超时默认为30秒,但如果您打开助手编辑器并显示时间线助手,则可以对其进行配置;超时在右下角。
例如,在Swift 3中(使用URLSession
而不是NSURLConnection
):
import UIKit
import PlaygroundSupport
let url = URL(string: "http://stackoverflow.com")!
URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data, error == nil else {
print(error ?? "Unknown error")
return
}
let contents = String(data: data, encoding: .utf8)
print(contents!)
}.resume()
PlaygroundPage.current.needsIndefiniteExecution = true
或者在Swift 2中:
import UIKit
import XCPlayground
let url = NSURL(string: "http://stackoverflow.com")
let request = NSURLRequest(URL: url!)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.currentQueue()) { response, maybeData, error in
if let data = maybeData {
let contents = NSString(data:data, encoding:NSUTF8StringEncoding)
println(contents)
} else {
println(error.localizedDescription)
}
}
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
发布于 2016-06-17 00:24:57
此API在Xcode8中再次更改,并被移至PlaygroundSupport
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
Session 213 at WWDC 2016中提到了这一变化。
发布于 2015-11-05 11:39:39
从XCode 7.1开始,不推荐使用XCPSetExecutionShouldContinueIndefinitely()
。现在这样做的正确方法是首先请求无限期执行作为当前页面的一个属性:
import XCPlayground
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
…然后指示执行何时完成,如下所示:
XCPlaygroundPage.currentPage.finishExecution()
例如:
import Foundation
import XCPlayground
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: "http://stackoverflow.com")!) {
result in
print("Got result: \(result)")
XCPlaygroundPage.currentPage.finishExecution()
}.resume()
https://stackoverflow.com/questions/24058336
复制相似问题