Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 311
GioB Avatar asked Jul 18 '16 08:07

GioB


People also ask

How to make purchases using IAP in Swift?

Go to the IAPManager.swift file and implement the following method: As you see, it’s as simple as that. We will call canMakePayments () method later on, when we’ll keep adding the missing parts from the demo app that will make purchases possible.

What is in-app purchase in iOS?

In-App Purchases in iOS With Swift 3 Introduction In-app purchase is a great feature for all those developers who want to get more revenue and offer extra content and features through their applications. For example, for games you...

What is in-app purchase?

Store Kit. Ivan is a programer at SoftwareCriollo.com where he writes Ruby, RubyMotion and Swift. When he is not writing code, you can find him Kiteboarding. In-App Purchase, or IAP for short, is a feature that gives developers the ability to sell content to the end user after their app has been downloaded.

How do I test in-app purchases on iOS simulator?

Sign In with your Sandbox User on your iOS device, navigate to your app and click the action to initiate the transaction. Don't worry about the price on the transaction window. Since you are using a Sandbox User, nothing will be charged from your account. NOTE: You can't test In-App Purchases on iOS Simulator.


Video Answer


2 Answers

WMios answer in Swift 3.

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: String?

override func viewDidLoad() {
    super.viewDidLoad()

    product_id = "YOUR_PRODUCT_ID"

    SKPaymentQueue.default().add(self)

    //Check if product is purchased
    if (UserDefaults.standard.bool(forKey: "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 as! Set<String>);
                productsRequest.delegate = self;
                productsRequest.start();
                print("Fetching Products");
            }else{
                print("Can't make purchases");
            }

}

Helper Methods

func buyProduct(product: SKProduct){
    print("Sending the Payment Request to Apple");
    let payment = SKPayment(product: product)
    SKPaymentQueue.default().add(payment);

}

Delegate Methods for IAP

func productsRequest (_ request: SKProductsRequest, didReceive response: SKProductsResponse) {

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


func request(_ request: SKRequest, didFailWithError error: Error) {
    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.default().finishTransaction(transaction as! SKPaymentTransaction)
                // Handle the purchase
                UserDefaults.standard.set(true , forKey: "purchased")
                //adView.hidden = true
                break;
            case .failed:
                print("Purchased Failed");
                SKPaymentQueue.default().finishTransaction(transaction as! SKPaymentTransaction)
                break;



            case .restored:
                print("Already Purchased");
                SKPaymentQueue.default().restoreCompletedTransactions()


                // Handle the purchase
                UserDefaults.standard.set(true , forKey: "purchased")
                //adView.hidden = true
                break;
            default:
                break;
            }
        }
    }

}

Restore Purchases

Add this to a function:

if (SKPaymentQueue.canMakePayments()) {
  SKPaymentQueue.default().restoreCompletedTransactions()
}
like image 194
Adnan Yusuf Avatar answered Oct 18 '22 18:10

Adnan Yusuf


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()
}
like image 42
Wyetro Avatar answered Oct 18 '22 19:10

Wyetro