Skip to content

Instantly share code, notes, and snippets.

@eddyekofo94
Created April 6, 2018 00:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eddyekofo94/7f23a4c860282acbe0c8f8cb0270ee36 to your computer and use it in GitHub Desktop.
Save eddyekofo94/7f23a4c860282acbe0c8f8cb0270ee36 to your computer and use it in GitHub Desktop.
//
// ViewController.swift
// JSON_Parsing_Tut
//
// Created by Eddy Ekofo on 05/04/2018.
// Copyright © 2018 eddyekofo.com. All rights reserved.
//
import UIKit
//
//struct Course: Decodable{
// let id:Int?
// let name: String?
// let imageUrl: String?
// let link:String?
//
//}
struct WebsiteDescription: Decodable {
let name: String
let description: String
let courses:[Course]
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//TODO: Change to desired url
let jsonUrlString = "https://api.example.com/user/id"
guard let url = URL(string: jsonUrlString) else{return}
URLSession.shared.dataTask(with: url) { (data, _, error) in
DispatchQueue.main.async {
if let error = error {
print("Failed to get data from url: ", error)
}
}
// Do everything else
guard let data = data else{
return
}
do{
// TODO: This code is for classes without arrays
let courses = try JSONDecoder().decode([Course].self, from: data)
print(courses)
// let websiteDescription = try JSONDecoder().decode(WebsiteDescription.self, from: data)
// print(websiteDescription)
// self.tableView.reloadData()
}catch let jsonError{
print("There is an error parsing JSON: ", jsonError)
}
}.resume() // fires the URLSession
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment