【问题标题】:swift 2 newbie : dataTaskWithRequest callback not executed? [duplicate]swift 2 新手:dataTaskWithRequest 回调未执行? [复制]
【发布时间】:2016-02-29 14:34:40
【问题描述】:

我是 Swift 新手,我已经学会了基本语法,我正在尝试做更高级的东西。 我对下面代码的第一次尝试是对 URL http://www.test.com 执行 HTTP 请求并获取响应:

//: Playground - noun: a place where people can play

import UIKit

var url : NSURL = NSURL(string: "http://www.test.com")!
var request: NSURLRequest = NSURLRequest(URL: url)
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
var responseString:NSString?;

let task : NSURLSessionDataTask = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
    print("toto")
    if error != nil {
        print("error=\(error)")
        return
    } else {
        print("response = \(response!)")
        responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)!
        print("responseString = \(responseString)")
    }

});

task.resume()
print (responseString)

当我在 Xcode 中运行代码时,没有打印“toto”并且 responseString 为 nil,知道发生了什么问题吗?

【问题讨论】:

    标签: swift swift2


    【解决方案1】:

    你在操场上运行它,你需要做一些额外的工作才能让异步任务运行。

    首先,导入 XCPlayground:

    import XCPlayground
    

    然后,在操场的最后,添加这一行:

    XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
    

    这可以让 Playground 继续执行,以便它可以等待您的完成块发生。

    对于 Xcode 8:

    import PlaygroundSupport
    
    PlaygroundPage.current.needsIndefiniteExecution = true
    

    【讨论】:

    • "... 在操场的末尾,添加这一行 ... – 添加行的位置无关紧要,可以在导入后的任何位置声明:-)
    • 它工作!谢谢你,快速大师:p
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-23
    • 2018-04-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多