GioB GioB - 4 months ago 37
Swift Question

Swift IOS 9 - Implement an in app purchase in the simplest way possible

i am trying to implement a single in-app purchase in my app to remove ads, from the iTunes Connect side is very easy but for the code part i find only tutorials with tableview and/or older version of swift or objC

I added the in-app purchase in iTunes Connect under the new version of the app,in the app i added a view with 2 buttons, one to purchase and the other to restore previous purchases, but i don't know the code, for now the inapp section of my viewcontroller is

import StoreKit

var productIDs: Array<String!> = []

var productsArray: Array<SKProduct!> = []

class ViewController: UIViewController, SKProductsRequestDelegate {


Is this ok?Do i need the arrays if I have only one in-app purchase?

I also added the in app purchase in the capabilities section but i have the red exclamation mark next to the label "add in app purchase entitlement to your app id",but i saw the same thing for the game center section and the leaderboards and achievements works so I think that i don't have to worry about it

Regarding the removal of the add, which is the best way?

I use admob and I was thinking to add an if statement in the Appdelegate and put the create and load interstital section inside it
In the code there is some variable set to true if the user made that purchase or I have to check it every time the user open the app?

Thank you in advance for your answers

Answer

The following works in Swift 2.

First, In Itunes Connect make an IAP

Import Storekit

import StoreKit

Add the StoreKit Delegates

class ViewController: UIViewController, SKProductsRequestDelegate, SKPaymentTransactionObserver {

Declare your product id

var product_id: NSString?

override func viewDidLoad() {


    product_id = "YOUR_PRODUCT_ID"
    super.viewDidLoad()
    SKPaymentQueue.defaultQueue().addTransactionObserver(self)

   //Check if product is purchased
   if (NSUserDefaults.standardUserDefaults().boolForKey("purchased")){

       // Hide ads
       adView.hidden = true

   } else {
       print("Should show ads...")

   }

}

Unlock Content: This is button action which will initialize purchase

@IBAction func unlockAction(sender: AnyObject) {

   print("About to fetch the product...")

// Can make payments
if (SKPaymentQueue.canMakePayments())
    {
        let productID:NSSet = NSSet(object: self.product_id!);
        let productsRequest:SKProductsRequest = SKProductsRequest(productIdentifiers: productID);
        productsRequest.delegate = self;
        productsRequest.start();
        println("Fetching Products");
    }else{
        print("Can't make purchases");
    }

}

Helper Methods

func buyProduct(product: SKProduct){
    println("Sending the Payment Request to Apple");
    let payment = SKPayment(product: product)
    SKPaymentQueue.defaultQueue().addPayment(payment);

 }

Delegate Methods for IAP

func productsRequest (request: SKProductsRequest, didReceiveResponse response: SKProductsResponse) {

    let count : Int = response.products.count
    if (count>0) {
        var validProduct: SKProduct = response.products[0] as SKProduct
        if (validProduct.productIdentifier == self.product_id) {
            print(validProduct.localizedTitle)
            print(validProduct.localizedDescription)
            print(validProduct.price)
            buyProduct(validProduct);
        } else {
            print(validProduct.productIdentifier)
        }
    } else {
        print("nothing")
    }
}


func request(request: SKRequest!, didFailWithError error: NSError!) {
    print("Error Fetching product information");
}

    func paymentQueue(_ queue: SKPaymentQueue,
updatedTransactions transactions: [SKPaymentTransaction])

{
    print("Received Payment Transaction Response from Apple");

    for transaction:AnyObject in transactions {
        if let trans:SKPaymentTransaction = transaction as? SKPaymentTransaction{
            switch trans.transactionState {
            case .Purchased:
                print("Product Purchased");
                SKPaymentQueue.defaultQueue().finishTransaction(transaction as SKPaymentTransaction)
                // Handle the purchase
                NSUserDefaults.standardUserDefaults().setBool(true , forKey: "purchased")
                adView.hidden = true
                break;
            case .Failed:
                print("Purchased Failed");
                SKPaymentQueue.defaultQueue().finishTransaction(transaction as SKPaymentTransaction)
                break;



            case .Restored:
                print("Already Purchased");
               SKPaymentQueue.defaultQueue().restoreCompletedTransactions() 


                 // Handle the purchase
                    NSUserDefaults.standardUserDefaults().setBool(true , forKey: "purchased")
                    adView.hidden = true
                    break;
            default:
                break;
            }
        }
    }

}

Restore Purchases

Add this to a function:

if (SKPaymentQueue.canMakePayments()) {
  SKPaymentQueue.defaultQueue().restoreCompletedTransactions()
}