I am new to swift and ios programming, I have the following block of code which queries the url for some songs and I should get the songs back.
let defaultSession = URLSession(configuration: URLSessionConfiguration.default)
var dataTask: URLSessionDataTask?
if dataTask != nil {
dataTask?.cancel()
}
let expectedCharSet = CharacterSet.urlQueryAllowed
let searchTerm = term.addingPercentEncoding(withAllowedCharacters: expectedCharSet)!
let url = URL(string: "https://itunes.apple.com/search?media=music&entity=song&term=\(term)")
print("URL: ", url)
// building up a dataTask computation
dataTask = defaultSession.dataTask( with: url!)
{(maybe_data, response, error) in
if error != nil {
print("Error: ", error!.localizedDescription)
// closure(nil)
return
} else if let httpResponse = response as? HTTPURLResponse {
print("no error")
if httpResponse.statusCode == 200 {
if let data = maybe_data {
// closure(songData)
print("songData: ", data)
} else {
print("no song data")
return
}
}
}
}
// does htis run the data task? is it a promise that's build?
dataTask?.resume()
The problem is that I want to get the data out of the completion handler, so ideally I'd write
let music = dataTask?.resume()
However, I am not sure how to output the value.