Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Check If User Has Already Made In-App Purchase? To Determine Their Access Level/Rights

I have a simple app, with one non-consumable in-app purchase option.

From my initial view controller I have a single 'enter' button.

This button will send a 'free' user (has not made non-consumable purchase) to one TabBarController "A" and series of views and a 'paid' user to the other TabBarController "B" a different set of views. These views will never intersect.

I would like to check wether my code is able to distinguish effectively as to whether a user has made the in-app purchase or otherwise.

Here is my code:

import UIKit
import StoreKit

class MainMainViewController: UIViewController, UIScrollViewDelegate, SKProductsRequestDelegate, SKPaymentTransactionObserver {

let defaults = NSUserDefaults.standardUserDefaults()
var product_id: NSString?;

...

  override func viewDidLoad() {

      product_id = "some.iap.id";
      SKPaymentQueue.defaultQueue().addTransactionObserver(self)


    super.viewDidLoad()
}

@IBAction func Enter(sender: AnyObject) {

    //Check if product is purchased
    if (defaults.boolForKey("purchased")){
         print("User has purchased da goods!")

        // Grant or otherwise full access based on whether user has purchased/not purchased.

        // Goto TabBarController A - FULL Access:
        let vc = self.storyboard!.instantiateViewControllerWithIdentifier("TabBarControllerPaid") as! TabBarControllerPaid
        self.presentViewController(vc, animated: true, completion: nil)
    }

    else if (!defaults.boolForKey("purchased")){
           print("user has NOT purchased yet")

        // Goto TabBarController B - PARTIAL Access:
        let vc = self.storyboard!.instantiateViewControllerWithIdentifier("TabBarControllerFree") as! TabBarControllerFree
        self.presentViewController(vc, animated: true, completion: nil)
   }


}

}

Many thanks in advance for any answers, comments or thoughts :-)

like image 227
Katherine Jenkins Avatar asked Mar 31 '16 02:03

Katherine Jenkins


1 Answers

Take a look at this tutorial, under the "Purchased Items" section.

It shows how to keep track of items that were purchased (and yes, you'll be using NSUserDefaults if you follow this tutorial closely), and you'll also learn how to restore previous purchases if the app is deleted or moved to a user's new device.

In your code up there, I see "defaults.boolForKey("purchased")". The big problem with this code that I can see is that it only allows for one item to be purchased (either the "purchased" boolean exists in NSUserDefaults or it doesn't).

like image 180
Michael Dautermann Avatar answered Oct 18 '22 11:10

Michael Dautermann