Advertisement
lcolli98

AllCoursesViewController.swift

Nov 11th, 2019
173
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 6.83 KB | None | 0 0
  1. //
  2. //  AllCoursesViewController.swift
  3. //  AeroBuddy
  4. //
  5. //  Created by Luke Collister on 01/09/2019.
  6. //  Copyright © 2019 Luke Collister. All rights reserved.
  7. //
  8.  
  9. import UIKit
  10. import StoreKit
  11.  
  12. class AllCoursesViewController: UITableViewController {
  13.    
  14.     // MARK: - Properties
  15.     var allCoursesArray = [Course]()
  16.     var ownedCoursesArray = [Course]()
  17.     var coursesToShow = [Course]()
  18.     var IDArray = [Int]()
  19.     var mycourse: Course!
  20.     var IAPArray = [SKProduct]()
  21.    
  22.     let dispatchGroup = DispatchGroup()
  23.    
  24.     @IBAction func unwindToAllCourses(segue: UIStoryboardSegue) {
  25.         DispatchQueue.main.async {
  26.             self.performSegue(withIdentifier: "loginToAllCoursesSegue", sender: nil)
  27.         }
  28.     }
  29.    
  30.     override func viewWillAppear(_ animated: Bool) {
  31.         let url = URL(string: "http://fe01.kilosierracharlie.me/user")
  32.         let task = URLSession.shared.dataTask(with: url!) {(data, response, error) in
  33.             guard error == nil else {
  34.                 print(error?.localizedDescription ?? "")
  35.                 return
  36.             }
  37.  
  38.             if let httpStatus = response as? HTTPURLResponse {
  39.                 // check status code returned by the http server
  40.                 print("status code = \(httpStatus.statusCode)")
  41.                 // process result
  42.                 if httpStatus.statusCode == 200 {
  43.                     // Do nada
  44.                    
  45.                 }
  46.                 else {
  47.                     // Segue to Login screen
  48.                     print("You need to log in")
  49.                     DispatchQueue.main.async {
  50.                         self.performSegue(withIdentifier: "allCoursesToLoginSegue", sender: self)
  51.                     }
  52.                 }
  53.             }
  54.         }
  55.         task.resume()
  56.     }
  57.    
  58.     override func viewDidLoad() {
  59.         super.viewDidLoad()
  60.         // Pull all owned courses, setting flags
  61.         parseOwnedCoursesJSON()
  62.         // Pull all courses
  63.         parseAllCoursesJSON()
  64.        
  65.         dispatchGroup.notify(queue: .main) {
  66.             // Merge both arrays, removing any duplicates where ID is present twice and flag is 0
  67.             for cou in self.ownedCoursesArray {
  68.                 self.IDArray.append(cou.id)
  69.             }
  70.             for var cou in self.allCoursesArray {
  71.                 cou.owned = self.IDArray.contains(cou.id)
  72.                 self.coursesToShow.append(cou)
  73.                 print("COURSES TO SHOW ...")
  74.                 print(self.coursesToShow)
  75.             }
  76.             self.tableView.reloadData()
  77.         }
  78.        
  79.         // IAP CODE
  80.         //IAPHandler.shared.setProductIDs(IDs: self.productIDs)
  81.         IAPHandler.shared.fetchAvailableProducts { [weak self](products)
  82.             in
  83.             guard let sSelf = self else {return}
  84.             sSelf.IAPArray = products
  85.         }
  86.     }
  87.    
  88.    
  89.     /*
  90.      Determines data to be displayed
  91.      1) Pull all courses
  92.      2) Pull all purchased courses
  93.      3) Loop through them, setting either an unlocked or locked flag/symbol
  94.      4) Populate table view based off this
  95.      */
  96.     // PULL ALL COURSES AND FILL ARRAY
  97.     func parseAllCoursesJSON() {
  98.         dispatchGroup.enter()
  99.        
  100.         let url = URL(string: "http://fe01.kilosierracharlie.me/courses")
  101.         let task = URLSession.shared.dataTask(with: url!) {(data, response, error) in
  102.            
  103.             // Check for errors
  104.             guard error == nil else {
  105.                 print("There was an error")
  106.                 return
  107.             }
  108.            
  109.             // Check for no data
  110.             guard let content = data else {
  111.                 print("There is no data to show")
  112.                 return
  113.             }
  114.            
  115.             // Using Codable, fill allCoursesArray
  116.             let decoder = JSONDecoder()
  117.            
  118.             do {
  119.                 for cou in try decoder.decode([Course].self, from: content) {
  120.                     self.allCoursesArray.append(cou)
  121.                     print(cou)
  122.                 }
  123.                 self.dispatchGroup.leave()
  124.                 return
  125.             }
  126.             catch {
  127.                 print(error.localizedDescription)
  128.                 print(error)
  129.                 return
  130.             }
  131.         }
  132.         task.resume()
  133.     }
  134.    
  135.    
  136.     // PULL ALL OWNED COURSES AND FILL THE ARRAY
  137.     func parseOwnedCoursesJSON() {
  138.         dispatchGroup.enter()
  139.  
  140.         let url = URL(string: "http://fe01.kilosierracharlie.me/courses/my")
  141.         let task = URLSession.shared.dataTask(with: url!) {(data, response, error) in
  142.            
  143.             // Check for errors
  144.             guard error == nil else {
  145.                 print("There was an error")
  146.                 return
  147.             }
  148.            
  149.             // Check for no data
  150.             guard let content = data else {
  151.                 print("There is no data to show")
  152.                 return
  153.             }
  154.            
  155.             // Using Codable, fill ownedCoursesArray and set the owned flag to true
  156.             let decoder = JSONDecoder()
  157.            
  158.             do {
  159.                 for cou in try decoder.decode([Course].self, from: content) {
  160.                     self.ownedCoursesArray.append(cou)
  161.                     print(cou)
  162.                 }
  163.                 for index in 0 ..< self.ownedCoursesArray.count {
  164.                     self.ownedCoursesArray[index].owned = true
  165.                 }
  166.                 self.dispatchGroup.leave()
  167.                 return
  168.             }
  169.             catch {
  170.                 print(error.localizedDescription)
  171.                 print(error)
  172.                 return
  173.             }
  174.         }
  175.         task.resume()
  176.     }
  177.    
  178.    
  179.     override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  180.         return self.coursesToShow.count
  181.     }
  182.    
  183.     override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  184.         let cell = tableView.dequeueReusableCell(withIdentifier: "CourseCell", for: indexPath) as! CourseCell
  185.         cell.course = coursesToShow[indexPath.row]
  186.         return cell
  187.     }
  188.    
  189.     // When the cell is pressed
  190.     override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  191.         // Determine which Course was selected
  192.         let selectedCourse = coursesToShow[indexPath.row]
  193.         mycourse = selectedCourse
  194.        
  195.         // Load the subjects for this course
  196.         performSegue(withIdentifier: "courseToSubjectSegue", sender: self)
  197.     }
  198.    
  199.     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  200.         if segue.identifier == "courseToSubjectSegue" {
  201.             if let destinationVC = segue.destination as? SubjectsViewController {
  202.                 destinationVC.courseVar = mycourse
  203.             }
  204.         }
  205.     }    
  206. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement