purchase in store kit in swift

To integrate In-App Purchase in a Swift-based iOS application, follow the steps below:

  1. Add StoreKit framework to your project.
  2. Create an identifier for your in-app purchase item using App Store Connect.
  3. Add the code snippet below to your view controller where you want to present the in-app purchase item to the user.
main.swift
// Replace "your_product_id" with the identifier you created in App Store Connect.
let productIdentifier = "your_product_id"

// Check if user is allowed to make payments.
if SKPaymentQueue.canMakePayments() {

   // Fetch available products from App Store.
   let request = SKProductsRequest(productIdentifiers: [productIdentifier])
   request.delegate = self
   request.start()
}
else {
   // Show an error message if user is not allowed to make payments.
   print("User is not allowed to make payments.")
}
510 chars
16 lines
  1. Implement SKProductsRequestDelegate protocol and add the code below to get the available products from App Store.
main.swift
func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
   let products = response.products

   if !products.isEmpty {
     // Present the product to the user for purchase.
     let product = products.first!
     let payment = SKPayment(product: product)
     SKPaymentQueue.default().add(payment)
   }
   else {
     print("No products available.")
   }
}
    
func request(_ request: SKRequest, didFailWithError error: Error) {
    print("Unable to fetch available products: \(error.localizedDescription)")
}
549 chars
18 lines
  1. Implement SKPaymentTransactionObserver protocol to process the transaction after the user makes a purchase.
main.swift
func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
        
    for transaction in transactions {
        switch transaction.transactionState {
        case .purchased:
            // Item purchased, handle the transaction and provide content to the user.
            SKPaymentQueue.default().finishTransaction(transaction)
            break
        case .failed:
            // Purchase failed, show an error message to the user.
            SKPaymentQueue.default().finishTransaction(transaction)
            break
        case .restored:
            // Purchase restored, handle the transaction and update content for the user.
            SKPaymentQueue.default().finishTransaction(transaction)
            break
        default:
            break
        }
    }
}
822 chars
22 lines
  1. Finally, add the following line of code to your app delegate's application(_:didFinishLaunchingWithOptions:) method to set the view controller as the observer of the payment queue.
main.swift
SKPaymentQueue.default().add(YOUR_VIEW_CONTROLLER_INSTANCE)
60 chars
2 lines

With these steps, you can present and process in-app purchases in a Swift-based iOS application using StoreKit.

gistlibby LogSnag