Skip to content

Instantly share code, notes, and snippets.

@tinacious
Created August 16, 2021 20:23
Show Gist options
  • Save tinacious/145ff30c2f4e03978942b7dae58796cf to your computer and use it in GitHub Desktop.
Save tinacious/145ff30c2f4e03978942b7dae58796cf to your computer and use it in GitHub Desktop.
Making network requests in iOS with URLSession.
// Create a playground called NetworkingPlayground, e.g.
// ./NetworkingPlayground.playground/Contents.swift
import UIKit
/*
{
"id": 1,
"title": "Vinyl gloves",
"merchant": "Shoppers Drug Mart",
"amount": 20,
"date": "2020-11-01T00:00:00.000Z",
"categoryId": 1
}
*/
struct Expense : Codable {
var id: Int
var title: String
var merchant: String
var date: String
var categoryId: Int
// When keys on the backend don't map to keys on the front-end
// enum CodingKeys : String, CodingKey { case firstName = "first_name" }
}
struct Expenses : Codable {
var data: [Expense]
}
let session = URLSession.shared
let url = URL(string: "https://aqueous-everglades-71468.herokuapp.com/expenses")!
let task = session.dataTask(with: url) { data, response, error in
if error != nil || data == nil {
print("There was an error")
return
}
guard let response = response as? HTTPURLResponse, (200...299).contains(response.statusCode) else {
print("Server error")
return
}
do {
let expenses = try JSONDecoder().decode(Expenses.self, from: data!)
for expense in expenses.data {
print(expense.title)
}
} catch let jsonError {
print("There was an error! \(jsonError)")
}
}
task.resume()
// Helpful resources:
// Making network requests with URLSession: https://learnappmaking.com/urlsession-swift-networking-how-to
// How to use Codable: https://learnappmaking.com/codable-json-swift-how-to
// Looping over a Codable: https://developer.apple.com/forums/thread/94317
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment