swift 2 新手:dataTaskWithRequest 回调未执行?
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是空的,对此有什么想法吗?