Advertisement
lcolli98

SubjectViewController

Feb 7th, 2020
591
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 9.27 KB | None | 0 0
  1. //
  2. //  SubjectsViewController.swift
  3. //  AeroBuddy
  4. //
  5. //  Created by Luke Collister on 15/09/2019.
  6. //  Copyright © 2019 Luke Collister. All rights reserved.
  7. //
  8.  
  9. /* This class should display the relevant subjects only, based on the selection of course from the previous TBVC */
  10.  
  11. import UIKit
  12. import StoreKit
  13.  
  14. class SubjectsViewController: UITableViewController, SKProductsRequestDelegate, SKPaymentTransactionObserver, SubjectCellDelegate  {
  15.  
  16.     // MARK: - Declarations
  17.     var courseVar: Course?
  18.     var subjectTableArray = [Subject]()
  19.     var subjectVar: Subject!
  20.     var mysubject: Subject!
  21.     let workingDG = DispatchGroup()
  22.    
  23.     var productsSet = Set<String>()
  24.     var displaySubjects = [Subject]()
  25.    
  26.    
  27.    
  28.     // MARK: - Buy Button Methods
  29.     func cellButtonTapped(cell: SubjectCell) {
  30.         // Trigger an alert to buy the subject
  31.         let alert = UIAlertController(title: "Purchase Subject?", message: "You do not own this subject. Do you wish to purchase it? Pressing \"Yes\" will purchase *all* topics within the subject.", preferredStyle: .alert)
  32.  
  33.         // Add the course product identifier to the set
  34.         let buttonPosition: CGPoint = cell.convert(CGPoint.zero, to: self.tableView)
  35.         let indexPath = self.tableView.indexPathForRow(at: buttonPosition)
  36.         productsSet.insert(displaySubjects[indexPath!.row].product_identifier!)
  37.         print("PRODUCTS SET: ", productsSet)
  38.  
  39.         // Yes option
  40.         alert.addAction(UIAlertAction(title: "Yes", style: .default, handler: { action in
  41.            // IAP Code Here
  42.            if (SKPaymentQueue.canMakePayments()) {
  43.                let productsRequest:SKProductsRequest = SKProductsRequest(productIdentifiers: self.productsSet)
  44.                productsRequest.delegate = self
  45.                productsRequest.start()
  46.                print("Fetching Products")
  47.            } else {
  48.                print("Can't make purchases")
  49.            }
  50.         }))
  51.         // No option
  52.         alert.addAction(UIAlertAction(title: "No", style: .cancel, handler: { action in
  53.             self.productsSet.removeAll()
  54.         }))
  55.  
  56.         self.present(alert, animated: true)
  57.         print("The subject with product identifier ", productsSet, " was selected!")
  58.     }
  59.    
  60.    
  61.    
  62.     // MARK: - IAP Methods
  63.     var product_identifier: String?
  64.    
  65.     func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
  66.         let count: Int = response.products.count
  67.         if (count > 0) {
  68.             let validProduct: SKProduct = response.products[0] as SKProduct
  69.             print(validProduct.localizedTitle)
  70.             print(validProduct.localizedDescription)
  71.             print(validProduct.price)
  72.             buyProduct(product: validProduct)
  73.         } else {
  74.             print("nothing")
  75.         }
  76.     }
  77.    
  78.     func buyProduct(product: SKProduct) {
  79.         print("Sending the Payment Request to Apple")
  80.         let payment = SKPayment(product: product)
  81.         SKPaymentQueue.default().add(payment)
  82.     }
  83.  
  84.     func request(_ request: SKRequest, didFailWithError error: Error) {
  85.         print("Error Fetching product information")
  86.     }
  87.  
  88.     func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
  89.         print("Received Payment Transaction Response from Apple")
  90.        
  91.         print("Transactions: ", transactions)
  92.  
  93.         for transaction: AnyObject in transactions {
  94.             if let trans:SKPaymentTransaction = transaction as? SKPaymentTransaction {
  95.                 switch trans.transactionState {
  96.                 case .purchased:
  97.                     print("Product Purchased")
  98.                     SKPaymentQueue.default().finishTransaction(transaction as! SKPaymentTransaction)
  99.                     // Handle the purchase
  100.                     UserDefaults.standard.set(true , forKey: "purchased")
  101.                     // Get the receipt if it's available
  102.                     if let appStoreReceiptURL = Bundle.main.appStoreReceiptURL, FileManager.default.fileExists(atPath: appStoreReceiptURL.path) {
  103.  
  104.                         do {
  105.                             let receiptData = try Data(contentsOf: appStoreReceiptURL, options: .alwaysMapped)
  106.                             print("RECEIPT DATA: ", receiptData)
  107.  
  108.                             let receiptString = receiptData.base64EncodedString(options: [])
  109.                             print("RECEIPT STRING: ", receiptString)
  110.  
  111.                             // Read receiptData
  112.                             // Create POST request
  113.                             let url = URL(string: "http://fe01.kilosierracharlie.me/verifypayment")!
  114.                             var request = URLRequest(url: url)
  115.                             request.httpMethod = "POST"
  116.                             request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
  117.                             let parameters: [String: Any] = [
  118.                                 "receipt": receiptString
  119.                             ]
  120.                             request.httpBody = parameters.percentEncoded()
  121.  
  122.                             // Send the data
  123.                             print("Before URLSession")
  124.                             let task = URLSession.shared.dataTask(with: request) { data, response, error in
  125.                                 guard let data = data, error == nil else {
  126.                                     print(error?.localizedDescription ?? "No data")
  127.                                     print("No data could be sent to the server. Please contact us.")
  128.                                     return
  129.                                 }
  130.                                 let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
  131.                                 if let responseJSON = responseJSON as? [String: Any] {
  132.                                     print(responseJSON)
  133.                                     //TO DO: Refresh if error false, else throw error
  134.                                 }
  135.                                 print("DATA: ", data)
  136.                             }
  137.                             print("Here")
  138.                             task.resume()
  139.                         }
  140.                         catch {
  141.                             print("Couldn't read receipt data with error: " + error.localizedDescription)
  142.                         }
  143.                     }
  144.                     break;
  145.                    
  146.                 case .failed:
  147.                     print("Purchased Failed")
  148.                     SKPaymentQueue.default().finishTransaction(transaction as! SKPaymentTransaction)
  149.                     break;
  150.  
  151.                 case .restored:
  152.                     print("Already Purchased")
  153.                     SKPaymentQueue.default().restoreCompletedTransactions()
  154.  
  155.                     // Handle the purchase
  156.                     UserDefaults.standard.set(true , forKey: "purchased")
  157.                     //adView.hidden = true
  158.                     break;
  159.                 default:
  160.                     print("In default")
  161.                     break;
  162.                 }
  163.             }
  164.         }
  165.     }
  166.    
  167.    
  168.    
  169.     // MARK: - UITableViewMethods
  170.     override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  171.        return self.displaySubjects.count
  172.     }
  173.  
  174.  
  175.     override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  176.        let cell = tableView.dequeueReusableCell(withIdentifier: "SubjectCell", for: indexPath) as! SubjectCell
  177.        cell.subject = displaySubjects[indexPath.row]
  178.        if (cell.subject?.owned == false) {
  179.            cell.backgroundColor = UIColor(red: 90/255, green: 90/255, blue: 90/255, alpha: 1)
  180.        } else {
  181.            //cell.backgroundColor = default
  182.        }
  183.        cell.delegate = self
  184.        return cell
  185.     }
  186.  
  187.    
  188.     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  189.         if segue.identifier == "subjectToTopicSegue" {
  190.             if let destinationVC = segue.destination as? TopicsViewController {
  191.                 destinationVC.subjectVar = mysubject
  192.             }
  193.         }
  194.     }
  195.  
  196.    
  197.     // When the cell is pressed
  198.     override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  199.        // Determine which Subject was selected
  200.        let selectedSubject = displaySubjects[indexPath.row]
  201.        mysubject = selectedSubject
  202.        print("Selected subject: ", displaySubjects[indexPath.row])
  203.      
  204.        // Load the subjects for this course
  205.        performSegue(withIdentifier: "subjectToTopicSegue", sender: self)
  206.     }
  207.    
  208.    
  209.    
  210.    
  211.     // MARK: - Default Methods
  212.     override func viewDidLoad() {
  213.         super.viewDidLoad()
  214.        
  215.         // Set the title based to the selected Course
  216.         self.title = courseVar?.title
  217.        
  218.         if var sject = courseVar!.subjects {
  219.             for sub in sject {
  220.                 displaySubjects.append(sub)
  221.             }
  222.         }
  223.        
  224.         // For all subjects, add product identifiers to allow IAPs
  225.         for subject in displaySubjects {
  226.             //subject.product_identifier = "com.aerobuddy.course.\(subject.id)"
  227.         }
  228.        
  229.         SKPaymentQueue.default().add(self)
  230.     }
  231. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement