我是Swift的新手,我已经学会了基本的语法,我正在尝试做更高级的事情。我第一次尝试使用下面的代码是在URL上执行一个http://www.test.com请求并获取响应:
//: 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是零,您知道出了什么问题吗?
发布于 2015-11-26 13:14:34
您正在操场上运行这个程序,您需要做一些额外的工作才能让异步任务运行。
首先,导入XCPlayground:
import XCPlayground然后,在操场的末尾,添加以下一行:
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true这样,操场就会继续执行,这样就可以等待完成块的发生。
对于Xcode 8:
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = truehttps://stackoverflow.com/questions/33939622
复制相似问题