Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // TopicsViewController.swift
- // AeroBuddy
- //
- // Created by Luke Collister on 26/09/2019.
- // Copyright © 2019 Luke Collister. All rights reserved.
- //
- /* This class should display the relevant topics only, based on the selection of subject from the previous TBVC */
- import UIKit
- import StoreKit
- class TopicsViewController: UITableViewController, SKProductsRequestDelegate, SKPaymentTransactionObserver, TopicCellDelegate {
- // MARK: - Declarations
- var subjectVar: Subject?
- var productsSet = Set<String>()
- var displayTopics = [Topic]()
- var allTopics = [Topic]()
- var ownedTopics = [Topic]()
- var mytopic: Topic!
- let workingDG = DispatchGroup()
- // MARK: - Buy Button Methods
- func cellButtonTapped(cell: TopicCell) {
- // Trigger an alert to buy the subject
- let alert = UIAlertController(title: "Purchase Topic?", message: "You do not own this topic. Do you wish to purchase it?", preferredStyle: .alert)
- // Add the topic product identifier to the set
- let buttonPosition: CGPoint = cell.convert(CGPoint.zero, to: self.tableView)
- let indexPath = self.tableView.indexPathForRow(at: buttonPosition)
- productsSet.insert(displayTopics[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 topic 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.displayTopics.count
- }
- override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
- let cell = tableView.dequeueReusableCell(withIdentifier: "TopicCell", for: indexPath) as! TopicCell
- cell.topic = displayTopics[indexPath.row]
- if (cell.topic?.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 == "topicToContentSegue" {
- if let destinationVC = segue.destination as? ContentViewController {
- destinationVC.topic = mytopic
- destinationVC.setup()
- }
- }
- }
- // When the cell is pressed
- override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
- // Determine which Topic was selected
- let selectedTopic = displayTopics[indexPath.row]
- mytopic = selectedTopic
- print("Selected subject: ", displayTopics[indexPath.row])
- // If owned, load the topic
- if (mytopic.owned == true) {
- print("My topic is owned, go to segue")
- performSegue(withIdentifier: "topicToContentSegue", sender: self)
- } else {
- print("My topic is not owned, show alert")
- let alert = UIAlertController(title: "Locked Content", message: "You must purchase this topic to be able to view its content.", preferredStyle: .alert)
- alert.addAction(UIAlertAction(title: "Return", style: .cancel, handler: { action in
- }))
- self.present(alert, animated: true)
- }
- }
- // MARK: - Default Methods
- override func viewDidLoad() {
- super.viewDidLoad()
- // Clear all arrays
- displayTopics.removeAll()
- allTopics.removeAll()
- ownedTopics.removeAll()
- // Set the title based to the selected Course
- self.title = subjectVar?.title
- // Get owned Topics
- DispatchQueue.global(qos: .background).async {
- self.workingDG.enter()
- self.getAllTopics(endpoint: "topics")
- self.workingDG.enter()
- self.getAllTopics(endpoint: "topics/my")
- self.workingDG.notify(queue: .main) {
- for i in 0 ..< self.ownedTopics.count {
- self.ownedTopics[i].owned = true
- }
- var idArray = [Int]()
- for topic in self.ownedTopics {
- idArray.append(topic.id)
- }
- for var topic in self.allTopics {
- topic.owned = idArray.contains(topic.id)
- // Display topics only in the selected subject
- if var topics = self.subjectVar!.topics {
- for top in topics {
- self.displayTopics.append(top)
- }
- }
- }
- self.tableView.reloadData()
- }
- }
- SKPaymentQueue.default().add(self)
- }
- // MARK: - JSON Methods
- func getAllTopics(endpoint: String) {
- let url = URL(string: "\(ServHandler.connectProtocol)://\(ServHandler.baseURL)/\(endpoint)")
- let task = URLSession.shared.dataTask(with: url!) {(data, response, error) in
- guard error == nil else {
- print("Error!")
- return
- }
- guard let content = data else {
- print("There is no data!")
- return
- }
- let decoder = JSONDecoder()
- do {
- for var topic in try decoder.decode([Topic].self, from: content) {
- if (endpoint == "topics") {
- topic.product_identifier = "com.aerobuddy.topic.\(topic.id)"
- self.allTopics.append(topic)
- }
- else {
- self.ownedTopics.append(topic)
- }
- }
- self.workingDG.leave()
- return
- }
- catch {
- print(error.localizedDescription)
- print(error)
- return
- }
- }
- task.resume()
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement