Asynchronous json retrieval

Hello,

I am getting an error message "Cannot convert value of type 'URLSessionDataTask' to expected argument type 'Data'" for the last line of this code. Please can you tell me what the problem is? Thank you

struct Item : Codable {
    var id: String
    var name: String
    var country: String
    var type: String
    var overallrecsit: String
    var dlastupd: String
    var doverallrecsit: String
}

    let url = URL(string:"https://www.TEST_URL.com/api_ios.php")
 
    let json = try? JSONDecoder().decode(Item.self, from: URLSession.shared.dataTask(with: url!))
Answered by darkpaw in 828158022

You're passing a data task into the method, rather than the data that it needs. The error message is quite explicit about that.

Try something like this:

let url = URL(string: "https://www.TEST_URL.com/api_ios.php")!
let config = URLSessionConfiguration.default
config.requestCachePolicy = .reloadIgnoringLocalAndRemoteCacheData

let session = URLSession.init(configuration: config)
session.dataTask(with: url) {(data, response, error) in
  do {
    if let json = data {
      if let decodedData = try? JSONDecoder().decode(Item.self, from: json) {
...
      }
    }
  }
}.resume()
Accepted Answer

You're passing a data task into the method, rather than the data that it needs. The error message is quite explicit about that.

Try something like this:

let url = URL(string: "https://www.TEST_URL.com/api_ios.php")!
let config = URLSessionConfiguration.default
config.requestCachePolicy = .reloadIgnoringLocalAndRemoteCacheData

let session = URLSession.init(configuration: config)
session.dataTask(with: url) {(data, response, error) in
  do {
    if let json = data {
      if let decodedData = try? JSONDecoder().decode(Item.self, from: json) {
...
      }
    }
  }
}.resume()
Asynchronous json retrieval
 
 
Q