【发布时间】: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,知道发生了什么问题吗?
【问题讨论】: