swift 2 新手:dataTaskWithRequest 回调未执行?

21 浏览
0 Comments

swift 2 新手:dataTaskWithRequest 回调未执行?

我是Swift的新手,已经学习了基本的语法,正在尝试做更高级的东西。

我在下面的代码中的第一次尝试是对URL http://www.test.com 发起一个HTTP请求并获取响应:

//:Playground - 名称:人们可以玩耍的地方

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是空的,对此有什么想法吗?

0
0 Comments

问题的原因是在playground中运行异步任务需要做一些额外的工作。解决方法是导入XCPlayground或者PlaygroundSupport,并在playground的结尾添加代码XCPlaygroundPage.currentPage.needsIndefiniteExecution = true或者PlaygroundPage.current.needsIndefiniteExecution = true,使playground保持执行状态以等待完成块的执行。

0