Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // ProVersionVideoViewController.swift
- // Piccole Ricette
- //
- // Created by Mattia Confalonieri on 02/01/18.
- // Copyright ยฉ 2018 42 srl. All rights reserved.
- //
- import UIKit
- import StoreKit
- import OneSignal
- import ASPVideoPlayer
- class ProVersionVideoViewController: UIViewController, SKProductsRequestDelegate, SKPaymentTransactionObserver {
- let statusBarWindow = UIApplication.shared.value(forKey: "statusBarWindow") as? UIWindow
- var productsRequest = SKProductsRequest()
- var iapProducts = [SKProduct]()
- var productID = ""
- @IBOutlet var actionButton : RoundedButton!
- @IBOutlet var priceLabel : UILabel!
- @IBOutlet var infoTexView : SuperTextView!
- @IBOutlet var closeButton : UIButton!
- @IBOutlet var videoPlayer: ASPVideoPlayerView!
- override func viewWillAppear(_ animated: Bool) {
- super.viewWillAppear(animated)
- //PRICE REQUEST
- let productIdentifiers : NSSet = NSSet(object: InAppPurchaseID.ProVersion);
- productsRequest = SKProductsRequest(productIdentifiers: productIdentifiers as! Set<String>)
- productsRequest.delegate = self
- productsRequest.start()
- }
- override func viewDidLoad() {
- super.viewDidLoad()
- // PLAY VIDEO
- let videoURL = Bundle.main.url(forResource: "pro_version_480p", withExtension: "mp4")
- videoPlayer.videoURL = videoURL
- videoPlayer.readyToPlayVideo = {
- self.videoPlayer.playVideo()
- }
- videoPlayer.startedVideo = {
- DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
- self.showClose()
- }
- }
- videoPlayer.error = { (error) -> Void in
- self.showClose()
- }
- // SETTA L'ALPHA DELLA NAVIGATION BAR E LA STATUS BAR BIANCA
- self.statusBarWindow?.alpha = 0
- self.navigationController?.setNavigationBarHidden(true, animated: false)
- if #available(iOS 11.0, *) {
- self.navigationItem.largeTitleDisplayMode = .never
- }
- //MARK: PRO VERSION
- let style = NSMutableParagraphStyle()
- style.alignment = NSTextAlignment.center
- let infoDictionary : [String : Any] = BundleFile.Generic!["pro video"] as! [String : Any]
- infoTexView.attributedText = NSMutableAttributedString(string: (infoDictionary["testo"] as? String)!, attributes: [ NSAttributedStringKey.font: TextStyle.RegularText! , NSAttributedStringKey.paragraphStyle: style] )
- actionButton!.setTitle("Acquista Piccole Ricette Pro", for: .normal)
- actionButton.isHidden = false
- priceLabel.textAlignment = .center
- priceLabel.textColor = Colors.Testo
- priceLabel.font? = TextStyle.LightText!
- priceLabel.numberOfLines = 1
- priceLabel.adjustsFontSizeToFitWidth = true
- priceLabel.minimumScaleFactor = 0.7
- }
- //SHOW CLOSE
- func showClose(){
- closeButton.isHidden = false
- }
- // PRICE REQUEST
- func productsRequest (_ request:SKProductsRequest, didReceive response:SKProductsResponse) {
- if (response.products.count > 0) {
- iapProducts = response.products
- let firstProduct = response.products[0] as SKProduct
- // RECUPERA IL PREZZO DALLO STORE
- let numberFormatter = NumberFormatter()
- numberFormatter.formatterBehavior = .behavior10_4
- numberFormatter.numberStyle = .currency
- numberFormatter.locale = firstProduct.priceLocale
- let price1Str = numberFormatter.string(from: firstProduct.price)
- // MOSTRA IL PREZZO NELLA LABEL
- if priceLabel != nil{
- priceLabel.text = "a soli \(price1Str!) per sempre"
- }
- }
- }
- // ACTION BUTTON
- @IBAction func actionButtonClick(){
- purchaseMyProduct(product: iapProducts[0])
- }
- // PURCHASE PRO VERSION
- func canMakePurchases() -> Bool { return SKPaymentQueue.canMakePayments() }
- func purchaseMyProduct(product: SKProduct) {
- videoPlayer.pauseVideo()
- if self.canMakePurchases() {
- let payment = SKPayment(product: product)
- SKPaymentQueue.default().add(self)
- SKPaymentQueue.default().add(payment)
- //print("Prodotto da acquistare: \(product.productIdentifier)")
- productID = product.productIdentifier
- } else {
- CustomAlertView.showGenericAlert(self,title: "Errore", message: "Questo dispositivo non รจ abilitato agli acquisti.",
- buttonTitle: nil,
- buttonCancel: "Chiudi",
- completion: { () -> Void in
- },
- cancel: { () -> Void in
- if self.videoPlayer.status == .paused{
- self.videoPlayer.playVideo()
- }
- })
- }
- }
- // PAYMENT QUEUE
- func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
- for transaction:AnyObject in transactions {
- if let trans = transaction as? SKPaymentTransaction {
- switch trans.transactionState {
- case .purchased:
- SKPaymentQueue.default().finishTransaction(transaction as! SKPaymentTransaction)
- if productID == InAppPurchaseID.ProVersion {
- // SALVATAGGIO UTENTE PRO SU ONE SIGNAL
- OneSignal.sendTag("user_type", value: "pro")
- // Attivo versione pro
- ParseManager.updateUserExtraInfo()
- CustomAlertView.showGenericAlert(self,title: "Successo", message: "Grazie per aver acquistato la versione Pro, goditi Piccole Ricette senza nessuna interruzione pubblicitaria.",
- buttonTitle: nil,
- buttonCancel: "Ok",
- completion: { () -> Void in
- },
- cancel: { () -> Void in
- UserDefaults.standard.set(true, forKey: "VersioneProAcquistata")
- self.chiudi()
- })
- }
- break
- case .failed:
- SKPaymentQueue.default().finishTransaction(transaction as! SKPaymentTransaction)
- // SHOW ERROR ALERT ONLY WHEN THE FAILURE IS NOT CAUSED BY CANCELL TAP
- if let error = transaction.error as? NSError {
- if error.domain == SKErrorDomain {
- if error.code != SKError.paymentCancelled.rawValue{
- CustomAlertView.showGenericAlert(self,title: "Errore", message: "Non รจ stato possibile eseguire l'acquisto.",
- buttonTitle: nil,
- buttonCancel: "Ok",
- completion: { () -> Void in
- },
- cancel: { () -> Void in
- if self.videoPlayer.status == .paused{
- self.videoPlayer.playVideo()
- }
- })
- }
- }
- }
- break
- case .restored:
- SKPaymentQueue.default().finishTransaction(transaction as! SKPaymentTransaction)
- // SALVATAGGIO UTENTE PRO SU ONE SIGNAL
- OneSignal.sendTag("user_type", value: "pro")
- ParseManager.updateUserExtraInfo()
- CustomAlertView.showGenericAlert(self,title: "Successo", message: "Avevi giร acquistato Piccole Ricette Pro. Abbiamo ripristinato l'acquisto senza nessun ulteriore pagamento.",
- buttonTitle: nil,
- buttonCancel: "Ok",
- completion: { () -> Void in
- },
- cancel: { () -> Void in
- UserDefaults.standard.set(true, forKey: "VersioneProAcquistata")
- self.chiudi()
- })
- break
- default: break
- }}}
- }
- // BACK
- @IBAction func chiudi(){
- self.dismiss(animated: true, completion: nil)
- }
- override func viewWillDisappear(_ animated: Bool) {
- super.viewWillDisappear(animated)
- videoPlayer.stopVideo()
- SKPaymentQueue.default().remove(self)
- // RIPRISTINO ALPHA NAVIGATION BAR E STATUS BAR ALPHA ALL'USCITA DALLA VISTA.
- self.navigationController?.setNavigationBarHidden(false, animated: false)
- self.statusBarWindow?.alpha = 1
- }
- override func didReceiveMemoryWarning() {
- super.didReceiveMemoryWarning()
- // Dispose of any resources that can be recreated.
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement