//
// HomeViewController.swift
// JsonText
//
// Created by Mohammad Azmal Hossain on 2/15/20.
// Copyright © 2020 Mohammad Azmal Hossain. All rights reserved.
//
import Foundation
import UIKit
/*
{
"name":"Lets Build That App",
"description":"Teaching and Building Apps since 1999",
"courses":[
{
"id":1,
"name":"Instagram Firebase",
"link":"https://www.letsbuildthatapp.com/course/instagram-firebase",
"imageUrl":"https://letsbuildthatapp-videos.s3-us-west-2.amazonaws.com/04782e30-d72a-4917-9d7a-c862226e0a93",
"number_of_lessons":49
},
{
"id":4,
"name":"Kindle Basic Training",
"link":"https://www.letsbuildthatapp.com/basic-training",
"imageUrl":"https://letsbuildthatapp-videos.s3-us-west-2.amazonaws.com/a6180731-c077-46e7-88d5-4900514e06cf_medium",
"number_of_lessons":19
}
]
}
*/
// MARK: - CoursesM
struct CoursesM: Codable {
let name, coursesMDescription: String?
let courses: [Course]
enum CodingKeys: String, CodingKey {
case name
case coursesMDescription = "description"
case courses
}
}
// MARK: - Course
struct Course: Codable {
let id: Int?
let name: String?
let link, imageURL: String?
let numberOfLessons: Int?
enum CodingKeys: String, CodingKey {
case id, name, link
case imageURL = "imageUrl"
case numberOfLessons = "number_of_lessons"
}
}
class HomeViewController: UIViewController {
var coursesArr : CoursesM?
@IBOutlet weak var homeTableView: UITableView!
func getRequestApiForCourse(){
let stringUrl = "http://api.letsbuildthatapp.com/jsondecodable/website_description"
let urlObj = URL(string: stringUrl)
guard let urlUnWrap = urlObj else {
return
}
let task = URLSession.shared.dataTask(with: urlUnWrap){(data, response, error) in
guard let dataG = data else {
return
}
do{
let coursesArrJson = try JSONDecoder().decode(CoursesM.self, from: dataG)
// for item in coursesArrJson.courses {
// print("azmal json = \(item.name)")
// }
self.coursesArr = coursesArrJson
} catch let errorJson {
print("azmal error = \(errorJson)")
}
DispatchQueue.main.async {
self.homeTableView.reloadData()
}
}
task.resume()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
getRequestApiForCourse()
setup()
}
func setup(){
let nib = UINib(nibName: "HomeTableViewCell", bundle: nil)
homeTableView.register(nib, forCellReuseIdentifier: "HomeTableViewCell")
homeTableView.delegate = self
homeTableView.dataSource = self
}
}
extension HomeViewController: UITableViewDelegate, UITableViewDataSource{
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return coursesArr?.courses.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "HomeTableViewCell", for: indexPath) as! HomeTableViewCell
cell.titleLabel.text = self.coursesArr?.name
cell.idLabel.text = "\(self.coursesArr?.courses[indexPath.row].id ?? 0)"
return cell
}
}