Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // SubjectsViewController.swift
- // AeroBuddy
- //
- // Created by Luke Collister on 15/09/2019.
- // Copyright © 2019 Luke Collister. All rights reserved.
- //
- /* This class should display the relevant subjects only, based on the selection of course from the previous TBVC */
- import UIKit
- import StoreKit
- class SubjectsViewController: UITableViewController, SKProductsRequestDelegate, SKPaymentTransactionObserver, SubjectCellDelegate {
- // MARK: - Declarations
- var courseVar: Course?
- var subjectTableArray = [Subject]()
- var subjectVar: Subject!
- var mysubject: Subject!
- let workingDG = DispatchGroup()
- var productsSet = Set<String>()
- var displaySubjects = [Subject]()
- // MARK: - Buy Button Methods
- func cellButtonTapped(cell: SubjectCell) {
- // Trigger an alert to buy the subject
- 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)
- // Add the course product identifier to the set
- let buttonPosition: CGPoint = cell.convert(CGPoint.zero, to: self.tableView)
- let indexPath = self.tableView.indexPathForRow(at: buttonPosition)
- productsSet.insert(displaySubjects[indexPath!.row].product_identifier!)
- print("PRODUCTS SET: ", productsSet)
- // Yes option
- alert.addAction(UIAlertAction(title: "Yes", style: .default, handler: { action in
- // IAP Code Here
- if (SKPaymentQueue.canMakePayments()) {
- let productsRequest:SKProductsRequest = SKProductsRequest(productIdentifiers: self.productsSet)
- productsRequest.delegate = self
- productsRequest.start()
- print("Fetching Products")
- } else {
- print("Can't make purchases")
- }
- }))
- // No option
- alert.addAction(UIAlertAction(title: "No", style: .cancel, handler: { action in
- self.productsSet.removeAll()
- }))
- self.present(alert, animated: true)
- print("The subject with product identifier ", productsSet, " was selected!")
- }
- // MARK: - IAP Methods
- var product_identifier: String?
- func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
- let count: Int = response.products.count
- if (count > 0) {
- let validProduct: SKProduct = response.products[0] as SKProduct
- print(validProduct.localizedTitle)
- print(validProduct.localizedDescription)
- print(validProduct.price)
- buyProduct(product: validProduct)
- } else {
- print("nothing")
- }
- }
- func buyProduct(product: SKProduct) {
- print("Sending the Payment Request to Apple")
- let payment = SKPayment(product: product)
- SKPaymentQueue.default().add(payment)
- }
- func request(_ request: SKRequest, didFailWithError error: Error) {
- print("Error Fetching product information")
- }
- func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
- print("Received Payment Transaction Response from Apple")
- print("Transactions: ", transactions)
- for transaction: AnyObject in transactions {
- if let trans:SKPaymentTransaction = transaction as? SKPaymentTransaction {
- switch trans.transactionState {
- case .purchased:
- print("Product Purchased")
- SKPaymentQueue.default().finishTransaction(transaction as! SKPaymentTransaction)
- // Handle the purchase
- UserDefaults.standard.set(true , forKey: "purchased")
- // Get the receipt if it's available
- if let appStoreReceiptURL = Bundle.main.appStoreReceiptURL, FileManager.default.fileExists(atPath: appStoreReceiptURL.path) {
- do {
- let receiptData = try Data(contentsOf: appStoreReceiptURL, options: .alwaysMapped)
- print("RECEIPT DATA: ", receiptData)
- let receiptString = receiptData.base64EncodedString(options: [])
- print("RECEIPT STRING: ", receiptString)
- // Read receiptData
- // Create POST request
- let url = URL(string: "http://fe01.kilosierracharlie.me/verifypayment")!
- var request = URLRequest(url: url)
- request.httpMethod = "POST"
- request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
- let parameters: [String: Any] = [
- "receipt": receiptString
- ]
- request.httpBody = parameters.percentEncoded()
- // Send the data
- print("Before URLSession")
- let task = URLSession.shared.dataTask(with: request) { data, response, error in
- guard let data = data, error == nil else {
- print(error?.localizedDescription ?? "No data")
- print("No data could be sent to the server. Please contact us.")
- return
- }
- let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
- if let responseJSON = responseJSON as? [String: Any] {
- print(responseJSON)
- //TO DO: Refresh if error false, else throw error
- }
- print("DATA: ", data)
- }
- print("Here")
- task.resume()
- }
- catch {
- print("Couldn't read receipt data with error: " + error.localizedDescription)
- }
- }
- break;
- case .failed:
- print("Purchased Failed")
- SKPaymentQueue.default().finishTransaction(transaction as! SKPaymentTransaction)
- break;
- case .restored:
- print("Already Purchased")
- SKPaymentQueue.default().restoreCompletedTransactions()
- // Handle the purchase
- UserDefaults.standard.set(true , forKey: "purchased")
- //adView.hidden = true
- break;
- default:
- print("In default")
- break;
- }
- }
- }
- }
- // MARK: - UITableViewMethods
- override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
- return self.displaySubjects.count
- }
- override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
- let cell = tableView.dequeueReusableCell(withIdentifier: "SubjectCell", for: indexPath) as! SubjectCell
- cell.subject = displaySubjects[indexPath.row]
- if (cell.subject?.owned == false) {
- cell.backgroundColor = UIColor(red: 90/255, green: 90/255, blue: 90/255, alpha: 1)
- } else {
- //cell.backgroundColor = default
- }
- cell.delegate = self
- return cell
- }
- override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
- if segue.identifier == "subjectToTopicSegue" {
- if let destinationVC = segue.destination as? TopicsViewController {
- destinationVC.subjectVar = mysubject
- }
- }
- }
- // When the cell is pressed
- override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
- // Determine which Subject was selected
- let selectedSubject = displaySubjects[indexPath.row]
- mysubject = selectedSubject
- print("Selected subject: ", displaySubjects[indexPath.row])
- // Load the subjects for this course
- performSegue(withIdentifier: "subjectToTopicSegue", sender: self)
- }
- // MARK: - Default Methods
- override func viewDidLoad() {
- super.viewDidLoad()
- // Set the title based to the selected Course
- self.title = courseVar?.title
- if var sject = courseVar!.subjects {
- for sub in sject {
- displaySubjects.append(sub)
- }
- }
- // For all subjects, add product identifiers to allow IAPs
- for subject in displaySubjects {
- //subject.product_identifier = "com.aerobuddy.course.\(subject.id)"
- }
- SKPaymentQueue.default().add(self)
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement