Home > Enterprise >  URLSession returns the size of the data instead of the actual contents of the data
URLSession returns the size of the data instead of the actual contents of the data

Time:11-29

I'm trying to learn how to use URLSession, so I'm trying to get the raw JSON from a URL as a consistency check that it worked. But I don't understand why it's outputting the data responses size in bytes instead of the actual data

Here's an example that I found online and modified to try and get it to return the JSON:

import UIKit
import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true


let url = URL(string: "http://date.jsontest.com/")!
let session = URLSession.shared
let q = session.dataTask(with: url) { data, response, error in
    do {
        print(data!)
    }
    catch {
        print("Error \(error)")
    }
}
q.resume()

This code returns something similar to 100 bytes, rather than the JSON itself. It doesn't make any sense, Apple's documentation says that data is "The data returned by the server.", so why is it returning the size of the data instead of the JSON of the URL?

CodePudding user response:

The result of a data task is always a Data object. It is up to you to work with it however you see fit.

For example, you could convert it into a string and print it to see what the server is sending back.

import UIKit
import Foundation
import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true


let url = URL(string: "http://date.jsontest.com/")!
let session = URLSession.shared
let q = session.dataTask(with: url) { data, response, error in
    do {
        let string = String(data: data!, encoding: .utf8)!
        print("Data as JSON: ")
        print(string) // Prints the actual JSON String.
    }
    catch {
        print("Error \(error)")
    }
}
q.resume()

Or perhaps more correctly you may want to parse into another object and get its properties:

import UIKit
import Foundation
import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

struct JSONTest: Codable {
    let date: String
    let time: String
}

let url = URL(string: "http://date.jsontest.com/")!
let session = URLSession.shared
let q = session.dataTask(with: url) { data, response, error in
    do {
        let jsonTest = try JSONDecoder().decode(JSONTest.self, from: data!)
        print("Date: \(jsonTest.date)") // Prints the `date` property of your JSON
    }
    catch {
        print("Error \(error)")
    }
}
q.resume()
  • To shorten the code, this question does not deal with optionals safely. Ensure you safely unwrap optionals if they can be nil.
  • Related