Reputation: 143
I have the following code:
var resultData:NSData?
task = session!.dataTaskWithRequest(request) { (data: NSData!, response: NSURLResponse!, error: NSError!) in
if ((error) != nil) {
println("Error")
return
}
resultData = data
}
task!.resume()
However, after execution the resultData is nil
. How can I get the data that's been returned by the request?
Upvotes: 1
Views: 1551
Reputation: 8669
Check if your data is nil and then you can use it
Here is a Swift 3 example:
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()
Upvotes: 2
Reputation: 1323
the dataTask will execute the function is an async, if you want to use the result data it has to be used inside the data task function. now the print statement will print the response. If you use resultData outside the dataTask func it will return 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()
Upvotes: -1