我有以下代码:
var resultData:NSData?
task = session!.dataTaskWithRequest(request) { (data: NSData!, response: NSURLResponse!, error: NSError!) in
if ((error) != nil) {
println("Error")
return
}
resultData = data
}
task!.resume()
但是,执行后resultData为nil
。如何获取请求返回的数据?
答案 0 :(得分:1)
检查您的数据是否为零,然后您可以使用
这是一个Swift 3示例:
let url = NSURL(string: "https://itunes.apple.com/search?term=jack+johnson&limit=2")!
let request = NSMutableURLRequest(url: url as URL)
let session = URLSession.shared
let task = session.dataTask(with: request as URLRequest) { data, response, error in
if error != nil {
print("error: \(error!.localizedDescription): \(String(describing: error))")
}
else if data != nil {
if let str = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) {
print("Received data:\n\(str)")
}
else {
print("unable to convert data to text")
}
}
}
task.resume()
答案 1 :(得分:-1)
dataTask将执行该函数是一个异步,如果要使用它必须在数据任务函数内使用的结果数据。现在print语句将打印响应。如果在dataTask func之外使用resultData,它将返回nil
var resultData:NSData?
let dataTask = session.dataTask(with: request as URLRequest) {
(data, response, error) in
guard let data = data, error == nil else { return }
if error != nil {
error
}
resultData = data
print(NSString(data: data, encoding: String.Encoding.utf8.rawValue)!)
}dataTask.resume()