我如何运行在游乐场异步回调 [英] How do I run Asynchronous callbacks in Playground

查看:130
本文介绍了我如何运行在游乐场异步回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

许多可可和CocoaTouch方法具有如在Objective-C块和密封件的雨燕实施完成回调。不过,在游乐场尝试这些出来的时候,完成永远不会被调用。例如:

Many Cocoa and CocoaTouch methods have completion callbacks implemented as blocks in Objective-C and Closures in Swift. However, when trying these out in Playground, the completion is never called. For example:

// 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 在我结束块永远不会叫......

I can see the console output in my Playground timeline, but the println in my completion block are never called...

推荐答案

虽然可以手动跑一跑环(或异步code,它不需要运行循环,使用其他方法等待调度一样信号灯),将内置的方式我们操场等待异步工作提供是导入 XCPlayground 框架和一套 XCPlaygroundPage.currentPage.needsIndefiniteExecution = TRUE 。如果这个属性被设置,当你的顶级游乐场源完成的,而不是停止操场那里,我们将继续旋转主运行循环,所以异步code有机会运行。我们最终会终止操场后的超时时间默认为30秒,但它可以,如果你打开​​助理编辑,并显示在时间轴助手进行配置;超时是在右下角。

While you can run a run loop manually (or, for asynchronous code that doesn't require a run loop, use other waiting methods like dispatch semaphores), the "built-in" way we provide in playgrounds to wait for asynchronous work is to import the XCPlayground framework and set XCPlaygroundPage.currentPage.needsIndefiniteExecution = true. If this property has been set, when your top level playground source finishes, instead of stopping the playground there we will continue to spin the main run loop, so asynchronous code has a chance to run. We will eventually terminate the playground after a timeout which defaults to 30 seconds, but which can be configured if you open the assistant editor and show the timeline assistant; the timeout is in the lower-right.

不幸的是,开发商preVIEW不包括 XCPlayground 适用于iOS;只为OSX。

Unfortunately, this developer preview does not include XCPlayground for iOS; only for OSX.

使用code有关工作的例子

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

这篇关于我如何运行在游乐场异步回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆