Last active
October 25, 2018 18:09
-
-
Save kalub92/de6e83ded9383deb67c66e170a9661a2 to your computer and use it in GitHub Desktop.
Using SWAPI to test out Codable (Encodable/Decodable) for JSON in Swift 4.2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
// Struct conforming to Codable and utilizing the CodingKeys enum to set up parameter to match how API data is organized. | |
struct Character: Codable { | |
let name: String | |
let height: String | |
let mass: String | |
let hairColor: String | |
enum CodingKeys: String, CodingKey { | |
case name | |
case height | |
case mass | |
case hairColor = "hair_color" | |
} | |
} | |
// Function to download data from SWAPI with URLSession and decode the JSON into a Character struct instance. | |
func downloadSWAPIData() { | |
let randomNum = Int.random(in: 1...88) | |
let swapiUrl = URL(string: "https://swapi.co/api/people/\(randomNum)")! | |
URLSession.shared.dataTask(with: swapiUrl) { (data, response, error) in | |
guard error == nil else { return } | |
guard let data = data else { return } | |
do { | |
let decoder = JSONDecoder() | |
let decodedData = try decoder.decode(Character.self, from: data) | |
// decodedData is of type Character | |
} catch { | |
print(error.localizedDescription) | |
} | |
}.resume() | |
} | |
downloadSWAPIData() | |
// Encoding a Character struct instance into a JSON object. | |
let character = Character(name: "Kylo Ren", height: "189", mass: "120", hairColor: "brown") | |
do { | |
let encoder = JSONEncoder() | |
let encodedData = try encoder.encode(character) | |
// encodedData is now a JSON object. | |
} catch { | |
print(error.localizedDescription) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment