The iOS App Sandbox plays a pivotal role in ensuring the secure testing of In-App Purchases (IAPs) without impacting real users. To utilize the sandbox, set up your app's IAPs in App Store Connect. Begin by importing the StoreKit framework and fetching product information using SKProductsRequest. Once products are retrieved, initiate purchases through SKPaymentQueue. Implement the SKPaymentTransactionObserver to handle transaction updates, distinguishing between successful, failed, and restored purchases. When testing, remember to use test user accounts and sign in to the App Store with a test account on your device. This ensures a controlled environment for validating IAPs during development.
URL - https://www.controlf5.in/ios-mobile-app-development-company/
swift Copy code import StoreKit
class YourViewController: UIViewController, SKProductsRequestDelegate, SKPaymentTransactionObserver {
func fetchProducts() {
let productIdentifiers: Set<String> = ["com.yourapp.product1", "com.yourapp.product2"]
let request = SKProductsRequest(productIdentifiers: productIdentifiers)
request.delegate = self
request.start()
}
func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
let products = response.products
// Handle retrieved products
}
func request(_ request: SKRequest, didFailWithError error: Error) {
// Handle error
}
func purchaseProduct(product: SKProduct) {
let payment = SKPayment(product: product)
SKPaymentQueue.default().add(payment)
}
func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
for transaction in transactions {
switch transaction.transactionState {
case .purchased:
// Handle successful purchase
case .failed:
// Handle failed purchase
case .restored:
// Handle restored purchase
default:
break
}
}
}
}