Advertisement
Guest User

Untitled

a guest
Aug 1st, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 9.93 KB | None | 0 0
  1. //
  2. //  ProVersionVideoViewController.swift
  3. //  Piccole Ricette
  4. //
  5. //  Created by Mattia Confalonieri on 02/01/18.
  6. //  Copyright ยฉ 2018 42 srl. All rights reserved.
  7. //
  8.  
  9. import UIKit
  10. import StoreKit
  11. import OneSignal
  12. import ASPVideoPlayer
  13.  
  14. class ProVersionVideoViewController: UIViewController, SKProductsRequestDelegate, SKPaymentTransactionObserver  {
  15.    
  16.     let statusBarWindow = UIApplication.shared.value(forKey: "statusBarWindow") as? UIWindow
  17.  
  18.     var productsRequest = SKProductsRequest()
  19.     var iapProducts = [SKProduct]()
  20.     var productID = ""
  21.    
  22.     @IBOutlet var actionButton : RoundedButton!
  23.     @IBOutlet var priceLabel : UILabel!
  24.     @IBOutlet var infoTexView : SuperTextView!
  25.     @IBOutlet var closeButton : UIButton!
  26.     @IBOutlet var videoPlayer: ASPVideoPlayerView!
  27.    
  28.     override func viewWillAppear(_ animated: Bool) {
  29.         super.viewWillAppear(animated)
  30.        
  31.         //PRICE REQUEST
  32.         let productIdentifiers : NSSet = NSSet(object: InAppPurchaseID.ProVersion);
  33.         productsRequest = SKProductsRequest(productIdentifiers: productIdentifiers as! Set<String>)
  34.         productsRequest.delegate = self
  35.         productsRequest.start()
  36.  
  37.     }
  38.    
  39.     override func viewDidLoad() {
  40.         super.viewDidLoad()
  41.        
  42.         // PLAY VIDEO
  43.         let videoURL = Bundle.main.url(forResource: "pro_version_480p", withExtension: "mp4")
  44.         videoPlayer.videoURL = videoURL
  45.         videoPlayer.readyToPlayVideo = {
  46.             self.videoPlayer.playVideo()
  47.         }
  48.         videoPlayer.startedVideo = {
  49.             DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
  50.                 self.showClose()
  51.             }
  52.         }
  53.         videoPlayer.error = { (error) -> Void in
  54.             self.showClose()
  55.         }
  56.        
  57.         // SETTA L'ALPHA DELLA NAVIGATION BAR E LA STATUS BAR BIANCA
  58.         self.statusBarWindow?.alpha = 0
  59.         self.navigationController?.setNavigationBarHidden(true, animated: false)
  60.        
  61.         if #available(iOS 11.0, *) {
  62.             self.navigationItem.largeTitleDisplayMode = .never
  63.         }
  64.                
  65.         //MARK: PRO VERSION
  66.         let style = NSMutableParagraphStyle()
  67.         style.alignment = NSTextAlignment.center
  68.         let infoDictionary : [String : Any] = BundleFile.Generic!["pro video"] as! [String : Any]
  69.         infoTexView.attributedText = NSMutableAttributedString(string: (infoDictionary["testo"] as? String)!, attributes: [ NSAttributedStringKey.font: TextStyle.RegularText! , NSAttributedStringKey.paragraphStyle: style] )
  70.        
  71.         actionButton!.setTitle("Acquista Piccole Ricette Pro", for: .normal)
  72.         actionButton.isHidden = false
  73.        
  74.         priceLabel.textAlignment = .center
  75.         priceLabel.textColor = Colors.Testo
  76.         priceLabel.font? = TextStyle.LightText!
  77.         priceLabel.numberOfLines = 1
  78.         priceLabel.adjustsFontSizeToFitWidth = true
  79.         priceLabel.minimumScaleFactor = 0.7
  80.     }
  81.    
  82.     //SHOW CLOSE
  83.     func showClose(){
  84.         closeButton.isHidden = false
  85.     }
  86.    
  87.     // PRICE REQUEST
  88.     func productsRequest (_ request:SKProductsRequest, didReceive response:SKProductsResponse) {
  89.         if (response.products.count > 0) {
  90.            
  91.             iapProducts = response.products
  92.             let firstProduct = response.products[0] as SKProduct
  93.            
  94.             // RECUPERA IL PREZZO DALLO STORE
  95.             let numberFormatter = NumberFormatter()
  96.             numberFormatter.formatterBehavior = .behavior10_4
  97.             numberFormatter.numberStyle = .currency
  98.             numberFormatter.locale = firstProduct.priceLocale
  99.             let price1Str = numberFormatter.string(from: firstProduct.price)
  100.            
  101.             // MOSTRA IL PREZZO NELLA LABEL
  102.             if priceLabel != nil{
  103.                 priceLabel.text = "a soli \(price1Str!) per sempre"
  104.             }
  105.         }
  106.     }
  107.    
  108.     // ACTION BUTTON
  109.     @IBAction func actionButtonClick(){
  110.         purchaseMyProduct(product: iapProducts[0])
  111.     }
  112.    
  113.     // PURCHASE PRO VERSION
  114.     func canMakePurchases() -> Bool {  return SKPaymentQueue.canMakePayments()  }
  115.     func purchaseMyProduct(product: SKProduct) {
  116.         videoPlayer.pauseVideo()
  117.         if self.canMakePurchases() {
  118.             let payment = SKPayment(product: product)
  119.             SKPaymentQueue.default().add(self)
  120.             SKPaymentQueue.default().add(payment)
  121.            
  122.             //print("Prodotto da acquistare: \(product.productIdentifier)")
  123.             productID = product.productIdentifier
  124.            
  125.         } else {
  126.             CustomAlertView.showGenericAlert(self,title: "Errore", message: "Questo dispositivo non รจ abilitato agli acquisti.",
  127.                                              buttonTitle: nil,
  128.                                              buttonCancel: "Chiudi",
  129.                                              completion: { () -> Void in
  130.             },
  131.                                              cancel: { () -> Void in
  132.                                                 if self.videoPlayer.status == .paused{
  133.                                                     self.videoPlayer.playVideo()
  134.                                                 }
  135.             })
  136.         }
  137.     }
  138.    
  139.     // PAYMENT QUEUE
  140.     func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
  141.         for transaction:AnyObject in transactions {
  142.             if let trans = transaction as? SKPaymentTransaction {
  143.                 switch trans.transactionState {
  144.                    
  145.                 case .purchased:
  146.                     SKPaymentQueue.default().finishTransaction(transaction as! SKPaymentTransaction)
  147.                     if productID == InAppPurchaseID.ProVersion {
  148.                         // SALVATAGGIO UTENTE PRO SU ONE SIGNAL
  149.                         OneSignal.sendTag("user_type", value: "pro")
  150.                         // Attivo versione pro
  151.                         ParseManager.updateUserExtraInfo()
  152.                         CustomAlertView.showGenericAlert(self,title: "Successo", message: "Grazie per aver acquistato la versione Pro, goditi Piccole Ricette senza nessuna interruzione pubblicitaria.",
  153.                                                          buttonTitle: nil,
  154.                                                          buttonCancel: "Ok",
  155.                                                          completion: { () -> Void in
  156.                         },
  157.                                                          cancel: { () -> Void in
  158.                                    UserDefaults.standard.set(true, forKey: "VersioneProAcquistata")
  159.                                                             self.chiudi()
  160.  
  161.                         })
  162.                     }
  163.                     break
  164.                 case .failed:
  165.                     SKPaymentQueue.default().finishTransaction(transaction as! SKPaymentTransaction)
  166.                     // SHOW ERROR ALERT ONLY WHEN THE FAILURE IS NOT CAUSED BY CANCELL TAP
  167.                     if let error = transaction.error as? NSError {
  168.                         if error.domain == SKErrorDomain {
  169.                             if error.code != SKError.paymentCancelled.rawValue{
  170.                                 CustomAlertView.showGenericAlert(self,title: "Errore", message: "Non รจ stato possibile eseguire l'acquisto.",
  171.                                                                  buttonTitle: nil,
  172.                                                                  buttonCancel: "Ok",
  173.                                                                  completion: { () -> Void in
  174.                                 },
  175.                                                                  cancel: { () -> Void in
  176.                                                                     if self.videoPlayer.status == .paused{
  177.                                                                         self.videoPlayer.playVideo()
  178.                                                                     }
  179.                                 })
  180.                             }
  181.                         }
  182.                     }
  183.                     break
  184.                 case .restored:
  185.                     SKPaymentQueue.default().finishTransaction(transaction as! SKPaymentTransaction)
  186.                     // SALVATAGGIO UTENTE PRO SU ONE SIGNAL
  187.                     OneSignal.sendTag("user_type", value: "pro")
  188.                     ParseManager.updateUserExtraInfo()
  189.                     CustomAlertView.showGenericAlert(self,title: "Successo", message: "Avevi giร  acquistato Piccole Ricette Pro. Abbiamo ripristinato l'acquisto senza nessun ulteriore pagamento.",
  190.                                                      buttonTitle: nil,
  191.                                                      buttonCancel: "Ok",
  192.                                                      completion: { () -> Void in
  193.                     },
  194.                                                      cancel: { () -> Void in
  195.                                         UserDefaults.standard.set(true, forKey: "VersioneProAcquistata")
  196.                                                         self.chiudi()
  197.                     })
  198.                     break
  199.                    
  200.                 default: break
  201.                 }}}
  202.     }
  203.    
  204.    
  205.     // BACK
  206.     @IBAction func chiudi(){
  207.         self.dismiss(animated: true, completion: nil)
  208.     }
  209.    
  210.     override func viewWillDisappear(_ animated: Bool) {
  211.         super.viewWillDisappear(animated)
  212.         videoPlayer.stopVideo()
  213.         SKPaymentQueue.default().remove(self)
  214.         // RIPRISTINO ALPHA NAVIGATION BAR E STATUS BAR ALPHA ALL'USCITA DALLA VISTA.
  215.         self.navigationController?.setNavigationBarHidden(false, animated: false)
  216.         self.statusBarWindow?.alpha = 1
  217.     }
  218.    
  219.     override func didReceiveMemoryWarning() {
  220.         super.didReceiveMemoryWarning()
  221.         // Dispose of any resources that can be recreated.
  222.     }
  223.  
  224. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement