应用内购买后启用按钮

Posted

技术标签:

【中文标题】应用内购买后启用按钮【英文标题】:Enable button after in-app purchase 【发布时间】:2017-05-09 13:03:49 【问题描述】:

我有一个分享按钮(“分享”),按 10 次后会挂断。要解锁它,您必须在应用程序中购买它。问题是当用户购买按钮时,我无法弄清楚如何解锁按钮。该按钮必须保持解锁状态。按下 10 次后不应被阻塞。如果您按下“恢复”按钮,则必须发生同样的事情。如果用户删除应用程序并重新安装,该按钮必须解锁。我请你帮忙。在这里,我将运行购买的代码放在应用程序和按钮的代码中

感谢大家并为初学者的问题道歉

为方便起见,我将这 2 个文件放在一个共享的保管箱链接中,每个人都可以访问 Dropbox (file swift)

代码按钮“分享”

var gif : GifModel? = nil


var imgView : UIImageView? = nil


override func viewDidLoad() 
    super.viewDidLoad()
    imgView = UIImageView(image: UIImage.gifImageWithURL(gif!.url!))
    imgView!.frame = CGRect(x: 0, y: 0, width: gif!.width, height: gif!.height)
    self.view.addSubview(imgView!)
    // Do any additional setup after loading the view.



override func viewDidLayoutSubviews() 
    imgView!.center = CGPoint(x: self.view.frame.size.width / 2, y: self.view.frame.size.height / 2)

override func didReceiveMemoryWarning() 
    super.didReceiveMemoryWarning()

    // Dispose of any resources that can be recreated.



func createAlert (title: String, message: String) 

    let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
    alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: 
        (action) in alert.dismiss(animated: true, completion: nil)))
    self.present(alert, animated: true, completion: nil)




@IBAction func share(sender: UIBarButtonItem) 


    var counter: Int = UserDefaults.standard.integer(forKey: "yourUniqueKey")
    if counter < 10 
        self.shareGifs(url: URL(string: gif!.url!)!)
        counter += 1
        UserDefaults.standard.set(counter, forKey: "yourUniqueKey")
     else 
        sender.isEnabled = false

        // alert qui!!! l'utente ha esaurito i 10 tap!
        createAlert(title: "OPS....", message: "In order to continue to share all the gifs you want and forever, you must purchase the 'Unlimited Gifs' pack")
    

代码应用内购买

extension IAPHelper 

public func requestProducts(completionHandler: @escaping ProductsRequestCompletionHandler) 
    productsRequest?.cancel()
    productsRequestCompletionHandler = completionHandler

    productsRequest = SKProductsRequest(productIdentifiers: productIdentifiers)
    productsRequest!.delegate = self
    productsRequest!.start()


public func buyProduct(_ product: SKProduct) 
    print("Buying \(product.productIdentifier)...")
    let payment = SKPayment(product: product)
    SKPaymentQueue.default().add(payment)


public func isProductPurchased(_ productIdentifier: ProductIdentifier) -> Bool 
    return purchasedProductIdentifiers.contains(productIdentifier)


public class func canMakePayments() -> Bool 
    return SKPaymentQueue.canMakePayments()


public func restorePurchases() 
    SKPaymentQueue.default().restoreCompletedTransactions()

extension IAPHelper: SKProductsRequestDelegate 

public func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) 
    let products = response.products
    print("Loaded list of products...")
    productsRequestCompletionHandler?(true, products)
    clearRequestAndHandler()

    for p in products 
        print("Found product: \(p.productIdentifier) \(p.localizedTitle) \(p.price.floatValue)")
    


public func request(_ request: SKRequest, didFailWithError error: Error) 
    print("Failed to load list of products.")
    print("Error: \(error.localizedDescription)")
    productsRequestCompletionHandler?(false, nil)
    clearRequestAndHandler()


private func clearRequestAndHandler() 
    productsRequest = nil
    productsRequestCompletionHandler = nil

extension IAPHelper: SKPaymentTransactionObserver 

public func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) 
    for transaction in transactions 
        switch (transaction.transactionState) 
        case .purchased:
            complete(transaction: transaction)
            break
        case .failed:
            fail(transaction: transaction)
            break
        case .restored:
            restore(transaction: transaction)
            break
        case .deferred:
            break
        case .purchasing:
            break
        
    


private func complete(transaction: SKPaymentTransaction) 
    print("complete...")
    deliverPurchaseNotificationFor(identifier: transaction.payment.productIdentifier)
    SKPaymentQueue.default().finishTransaction(transaction)


private func restore(transaction: SKPaymentTransaction) 
    guard let productIdentifier = transaction.original?.payment.productIdentifier else  return 

    print("restore... \(productIdentifier)")
    deliverPurchaseNotificationFor(identifier: productIdentifier)
    SKPaymentQueue.default().finishTransaction(transaction)


private func fail(transaction: SKPaymentTransaction) 
    print("fail...")
    if let transactionError = transaction.error as NSError? 
        if transactionError.code != SKError.paymentCancelled.rawValue 
            print("Transaction Error: \(String(describing: transaction.error?.localizedDescription))")
        
    

    SKPaymentQueue.default().finishTransaction(transaction)


private func deliverPurchaseNotificationFor(identifier: String?) 
    guard let identifier = identifier else  return 

    purchasedProductIdentifiers.insert(identifier)
    UserDefaults.standard.set(true, forKey: identifier)
    UserDefaults.standard.synchronize()
    NotificationCenter.default.post(name: NSNotification.Name(rawValue: IAPHelper.IAPHelperPurchaseNotification), object: identifier)

【问题讨论】:

请在您的问题中输入相关代码 我放它没问题,但它很长。出于这个原因,我更喜欢简化放置 Dropbox。反正我现在放了 完成 ;) 添加代码 【参考方案1】:

您最好的选择是在购买发生时将一个值存储到 NSUserDefaults 中,然后加载您的视图,对该值进行简单检查以查看它是否已购买,然后限制或不限制按下次数这可能发生。

在完成代码中设置它

[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"IAPPurcashed"
[[NSNotificationCenter defaultCenter] postNotificationName:@"IAP" object:self];

那么在你看来

([[NSUserDefaults standardUserDefaults] bookForKey:@"IAPPurcashed"] == YES 

    *unlock IAP for multiple presses*

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ReloadIAPButton:) name:@"IAP" object:nil];``

还为通知中心添加您的观察者,以重新加载您可能需要的任何按钮。

【讨论】:

请尽快... :(

以上是关于应用内购买后启用按钮的主要内容,如果未能解决你的问题,请参考以下文章

禁用/隐藏应用内购买

为新版本的应用启用应用内购买?

如果购买成功,如何在应用内购买中启用专业功能

重新启动后应用程序重置

了解用户在应用内购买期间何时按下了取消按钮

通过应用内购买启用今日视图小部件