加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何在Playground中运行异步回调

发布时间:2020-12-14 06:12:16 所属栏目:百科 来源:网络整理
导读:许多Cocoa和CocoaTouch方法具有在Objective-C和Closures中实现为块的完成回调。但是,当在Playground中尝试这些时,完成不会被调用。例如: // Playground - noun: a place where people can playimport Cocoaimport XCPlaygroundlet url = NSURL(string: "h
许多Cocoa和CocoaTouch方法具有在Objective-C和Closures中实现为块的完成回调。但是,当在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)
    }
}

我可以在我的Playground时间轴看到控制台输出,但在我的完成块中的println从来不叫…

虽然你可以手动运行一个运行循环(或者,对于不需要运行循环的异步代码,使用其他等待方法,如dispatch semaphores),我们在playgrounds中提供的等待异步工作的“内置”方法是:导入XCPlayground框架并设置XCPlaygroundPage.currentPage.needsIndefiniteExecution = true。如果这个属性已经设置,当你的顶级playground源完成,而不是停止playground,我们将继续旋转主运行循环,所以异步代码有机会运行。我们最终将在超时后终止playground,默认为30秒,但如果您打开助理编辑器并显示时间轴助手,可以配置;超时在右下方。

不幸的是,这个开发者预览不包括iOS的XCPlayground;仅适用于OSX。

使用有问题的代码的工作示例

import UIKit
import XCPlayground

let url = NSURL(string: "http://stackoverflow.com")
let request = NSURLRequest(URL: url!)

NSURLConnection.sendAsynchronousRequest(request,queue: NSOperationQueue.currentQueue()) { response,error in
    if let data = maybeData {
        let contents = NSString(data:data,encoding:NSUTF8StringEncoding)
        println(contents)
    } else {
        println(error.localizedDescription)
    }
}

XCPlaygroundPage.currentPage.needsIndefiniteExecution = true

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读