Skip to content

URLSession

Norman Basham edited this page Feb 17, 2020 · 1 revision

URLSession

Source


Use URLSession.shared.runTask instead of URLSession.shared.dataTask when using Result<Data, NetworkError>. This will handle error checking, allow for logging, and handle Codable. You also don't have to remember to run task.resume() ;-).

let req = URLRequest.createGet(url: self)
URLSession.shared.runTask(with: req) { result in
    switch result {
    case .success(let data):
        completion(data)
    case .failure(let err):
        completion(err)
    }
}

Turn on logging with URLSession.shared.log() to see information about network requests and responses. Turn logging off with URLSession.shared.log(false). Example output:

    POST 
    http://localhost:3000/pets
    headers: ["Content-Type": "application/json"]
    Success {
      "name": "Dawn",
      "id": 1
    }
Clone this wiki locally