iOS In-App Purchase

Here we will learn iOS in-app purchase in swift with example and how to use in-app purchase subscription in ios swift applications to get payments from users to enable additional features with an example using Xcode.

iOS In-App Purchase

In iOS In-App Purchase is a storekit framework which is used to embed the store inside of our app. Generally, the in-app purchase feature in iOS is used to collect the payments from users for additional features and content.

 

Suppose we have iOS swift application and allowing users to access only limited features for free in case if they want to access all the features and content in the app they should pay for it. By using in-app purchase we can collect the payments from users to enable full features and content of our app.

 

Another example to use in-app purchase is we created one iOS app and allowing users to access all the content and features of an app for free but we are displaying advertisements in our app. In case if users are not interested to see advertisement then they can pay the amount to enable remove ads feature in our application. In our iOS app by using in-app purchase we can collect all these payments to enable additional features like removing ads from the app, etc.

 

Now we will see how to implement the iOS in-app purchase option in our swift applications with example.

Create iOS Transitions App in Swift

To create a new project in iOS open Xcode from /Applications folder directory. Once we open Xcode the welcome window will open like as shown below. In the welcome window click on the second option “Create a new Xcode Project” or choose File à New à Project.

 

Xcode application to create ios project

 

 After selecting “Create a new Xcode project” a new window will open in that we need to choose a template.

 

The new Xcode window will contain several built-in app templates to implement the common type of iOS apps like page-based apps, tab-based apps, games, table-view apps, etc. These templates are having a pre-configured interface and source code files. 

 

For this iOS In-App Purchase example, we will use the most basic template “Single View Application”. To select this one, Go to the iOS section on the left side à select Application à In the main area of dialog select “Single View Application” and then click on the next button like as shown below.

 

Select single view application from ios xcode templates

 

After click Next we will get a window like as shown below, in this we need to mention project name and other details for our application.

 

Product Name: “In App Purchase”

 

The name whatever we enter in the Product Name section will be used for the project and app.

 

Organization Name: “Tutlane”

 

You can enter the name of your organization or your own name or you can leave it as blank.

 

Organization Identifier: “com.developersociety”

 

Enter your organization identifier in case if you don't have any organization identifier enter com.example.

 

Bundle Identifier: This value will generate automatically based on the values we entered in Product Name and Organization Identifier.

 

Language: “Swift”

 

Select language type as “Swift” because we are going to develop applications using swift.

 

Devices: “Universal”

 

Choose Devices options as Universal it means that one application is for all Apple devices in case if you have any specific requirement to run an app only for iPad then you can choose the iPad option to make your application restricted to run only on iPad devices.

 

Use Core Data: Unselected

 

This option is used for database operations. In case if you have any database related operations in your application select this option otherwise unselect the option.

 

Include Unit Tests: Unselected

 

In case if you need unit tests for your application then select this option otherwise unselect it.

 

Include UI Tests: Unselected

 

In case if you need UI tests for your application then select this option otherwise unselect it.

 

Once you finished entering all the options then click on the Next button like as shown below.

 

create new ios in app purchase application in swift

 

Once we click on Next button new dialog will open in that we need to select the location to save our project. Once you select the location to save the project then click on Create button like as shown below

 

Give path to save new ios application in xcode

 

After clicking on the Create button, the Xcode will create and open a new project. In our project, Main.storyboard and ViewController.swift are the main files that we used to design an app user interface and to maintain source code. 

 

Main.storyboard - Its visual interface editor and we will use this file to design our app user interface 

 

ViewController.swift - It contains the source code of our application and we use this file to write any code related to our app.

 

Now in project select Main.storyboard file, the Xcode will open visual interface editor like as shown below.

 

ios in app purchase app storyboard file in xcode

 

Now select ViewController.Swift file in your project that view will be like as shown below.

 

ios in-app purchase app viewcontroller.swift file in xcode

Add iOS UI Controls to View in Swift

Now we will add controls to our application for that open Object Library. The Object Library will appear at the bottom of Xcode in the right side. In case if you don't find Object library, click on the button which is in the third position from the left in the library selector bar like as shown below. (Alternatively you can choose View à Utilities à Show Object Library.)

 

Object Library in Xcode Application to Search for UI Controls

 

As we discussed our user interface will be in Main.storyboard file so open Main.storyboard file. Now in Object library search for Label in Filter field then drag and drop Label into Main.storyboard ViewController like as shown below same way add another label and 3 button controls in our Main.storyboard file.

 

ios in app purchase add controls to app in xcode

Connect iOS UI Controls to Code in Swift

Now we will make a connection between controls and ViewController.swift code for that click on the assistant button (overlap circle) in Xcode toolbar right side corner like as shown below

 

Assistant Editor in iOS Xcode to Mapp Controls with Code

 

To map the controls, press the Ctrl button in the keyboard and drag the labels and buttons from view controller and drop into ViewController.swift file like as shown below.

 

ios in-app purchase app map controls to viewcontroller.swift file in xcode

 

Once we did all the settings we need to write custom code to enable few features for users based on their purchase using in-app purchase for that we need to write code in ViewController.swift file like as shown below.

 

import UIKit

import StoreKit

class ViewController: UIViewController, SKProductsRequestDelegate, SKPaymentTransactionObserver

{

@IBOutlet var Ad: UILabel!

@IBOutlet var CAmount: UILabel!

@IBOutlet var RemoveAd: UIButton!

@IBOutlet var AddCoin: UIButton!

var coins = 50

overridefunc viewDidLoad() {

super.viewDidLoad()

RemoveAd.enabled = false

AddCoin.enabled = false

if(SKPaymentQueue.canMakePayments()) {

print("IAP is enable, loading")

let productID:NSSet = NSSet(objects: "seemu.iap.addcoins", "seemu.iap.removeads")

let request: SKProductsRequest = SKProductsRequest(productIdentifiers: productID as! Set<String>)

request.delegate = self

request.start()

} else {

print("please enable IAPS")

}

}

@IBAction func btnRemoveAds(sender: UIButton) {

for product in list {

let prodID = product.productIdentifier

if(prodID == "seemu.iap.removeads") {

p = product

buyProduct()

break;

}

}

}

@IBAction func btnAddCoins(sender: UIButton) {

for product in list {

let prodID = product.productIdentifier

if(prodID == "seemu.iap.addcoins") {

p = product

buyProduct()

break;

}

}

}

func removeAds() {

Ad.removeFromSuperview()

}

func addCoins() {

coins = coins + 50

CAmount.text = "\(coins)"

}

override func didReceiveMemoryWarning() {

super.didReceiveMemoryWarning()

// Dispose of any resources that can be recreated.

}

@IBAction func RestorePurchases(sender: UIButton) {

SKPaymentQueue.defaultQueue().addTransactionObserver(self)

SKPaymentQueue.defaultQueue().restoreCompletedTransactions()

}

var list = [SKProduct]()

var p = SKProduct()

func buyProduct() {

print("buy " + p.productIdentifier)

let pay = SKPayment(product: p)

SKPaymentQueue.defaultQueue().addTransactionObserver(self)

SKPaymentQueue.defaultQueue().addPayment(pay as SKPayment)

}

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

print("Product Is Request")

let myProduct = response.products 

for product in myProduct {

print("Product are Added")

print(product.productIdentifier)

print(product.localizedTitle)

print(product.localizedDescription)

print(product.price)

list.append(product )

}

RemoveAd.enabled = true

AddCoin.enabled = true

}

func paymentQueueRestoreCompletedTransactionsFinished(queue: SKPaymentQueue) {

print("Transactions Restore Sucessfully")

for transaction in queue.transactions {

let t: SKPaymentTransaction = transaction

let prodID = t.payment.productIdentifierasString

switch prodID {

case"seemu.iap.removeads":

print("remove ads")

removeAds()

case"seemu.iap.addcoins":

print("The Coins are add to account")

addCoins()

default:

print("IAP not setup Correctly")

}

}

}

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

print("add paymnet")

for transaction:AnyObject in transactions {

let trans = transaction as! SKPaymentTransaction

print(trans.error)

switch trans.transactionState {

case .Purchased:

print("buy, ok unlock iap here")

print(p.productIdentifier)

let prodID = p.productIdentifier as String

switch prodID {

case"seemu.iap.removeads":

print("remove ads")

removeAds()

case"seemu.iap.addcoins":

print("add coins to account")

addCoins()

default:

print("IAP not setup")

}

queue.finishTransaction(trans)

break;

case .Failed:

print("buy error")

queue.finishTransaction(trans)

break;

default:

print("default")

break;

}

}

}

func finishTransaction(trans:SKPaymentTransaction)

{

print("finish trans")

SKPaymentQueue.defaultQueue().finishTransaction(trans)

}

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

{

print("remove trans");

}

}

Now we will run and check the output of application. To run application, select the required simulator (Here we selected iPhone 6s Plus) and click on Play button, located at the top-left corner of the Xcode toolbar like as shown below.

 

Run ios scroll view application using xcode editor

Output of iOS In-App Purchase in Swift

Following is the result of iOS in-app purchase in swift. Now you click on add coins, give the Apple ID and purchase the coins. If you have already an Apple ID give the username and password here.

 

ios in-app purchase app example result or output

 

In case if you don’t have account on apple. Go to the Apple Account Registration and register your account on Apple first then create an Apple ID. by using the given URL.