In-App Purchases in ios
In-app purchase
This process is well known as In App Purchase (IAP), is a great way to earn the money :-) from your iOS or MacOS applications.
Types Of In App Purchases:
Consumable
Non-consumable
Non-renewing subscriptions
Auto-renewable subscriptions
Basically we are working on Consumable In App Purchases
1 :- Firstly create new Project
2 :- Add NewFile Configuration.storekit (StoreKit) Toggle(switch Button)
3 :- Create tableView and take one
4 :- Create more file where (IPAManager) import StoreKit
LET’ s Come to Code
Lets Come in IPAManager.file
Import File
import Foundation
Import StoreKit
Class
final class IPAManager : NSObject , SKProductsRequestDelegate , SKPaymentTransactionObserver {
/*
*/
}
Create dictionary
var products = [SKProduct]()
Create completion
private var completion :((Int) -> Void)?
Create NSobject of enum
enum Product : String , CaseIterable {
case dimond_500
case dimond_1000
case dimond_2000
case dimond_5000
var count: Int {
switch self {
case .dimond_500:
return 500
case .dimond_1000:
return 1000
case .dimond_2000:
return 2000
case .dimond_5000:
return 5000
}
}
}
# SKProductsRequestDelegate
public func featchProduct () {
let request = SKProductsRequest(productIdentifiers:
Set(Product.allCases.compactMap({ $0.rawValue })))
request.delegate = self
request.start()
}
func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
print("response.products.count\(response.products.count)")
self.products = response.products
}
public func purchase(product :Product , completion : @escaping ((Int) -> Void)) {
guard SKPaymentQueue.canMakePayments() else {
return
}
guard let storekitProduct = products.first(where: { $0.productIdentifier == product.rawValue}) else {
return
}
self.completion = completion
let paymentRequest = SKPayment(product: storekitProduct)
SKPaymentQueue.default().add(self)
SKPaymentQueue.default().add(paymentRequest)
}
#SKPaymentTransactionObserver
func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
transactions.forEach({
switch $0.transactionState {
case .purchasing:
break
case .purchased:
if let product = Product(rawValue: $0.payment.productIdentifier){
completion?(product.count)
var valuetrue = true
UserDefaults.standard.set(valuetrue, forKey: "num")
}
SKPaymentQueue.default().finishTransaction($0)
SKPaymentQueue.default().remove(self)
case .failed:
break
case .restored:
break
case .deferred:
break
@unknown default:
break
}
}
)
}
#ViewController
import UIKit
struct Model {
let title : String
let handler :(() -> Void)
}
class ViewController: UIViewController {
@IBOutlet weak var toggle: UISwitch!
@IBOutlet weak var tableView: UITableView!
var models = [Model]()
override func viewDidLoad() {
super.viewDidLoad()
toggle.isEnabled = false
models.append(Model(title: "500 Diamond", handler: {
IPAManager.shared.purchase(product: .dimond_500) { [weak self] count in
DispatchQueue.main.async {
let currentCount = self?.mydiamondcount ?? 0
let newCount = currentCount + count
UserDefaults.standard.setValue(newCount, forKey: "diamond_Count")
if currentCount < newCount ˀ
self?.toggleHideshow()
}
}
}
}))
models.append(Model(title: "1000 Diamond", handler: {
IPAManager.shared.purchase(product: .dimond_1000){ [weak self] count in
DispatchQueue.main.async {
let currentCount = self?.mydiamondcount ?? 0
let newCount = currentCount + count
UserDefaults.standard.setValue(newCount, forKey: "diamond_Count")
if currentCount < newCount {
self?.toggleHideshow()
}
}
}
}))
models.append(Model(title: "2000 Diamond", handler: {
IPAManager.shared.purchase(product: .dimond_2000){ [weak self] count in
DispatchQueue.main.async {
let currentCount = self?.mydiamondcount ?? 0
let newCount = currentCount + count
UserDefaults.standard.setValue(newCount, forKey: "diamond_Count")
if currentCount < newCount {
self?.toggleHideshow()
}
}
}
}))
models.append(Model(title: "5000 Diamond", handler: {
IPAManager.shared.purchase(product: .dimond_5000){ [weak self] count in
DispatchQueue.main.async {
let currentCount = self?.mydiamondcount ?? 0
let newCount = currentCount + count
UserDefaults.standard.setValue(newCount, forKey: "diamond_Count")
if currentCount < newCount {
self?.toggleHideshow()
}
}
}
}))
view.addSubview(tableView)
tableView.delegate = self
tableView.dataSource = self
tableView.frame = view.bounds
// setupHeader()
}
}
extension ViewController : UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return models.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let model = models[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = model.title
cell.imageView?.image = UIImage(systemName: "heart.fill")
cell.imageView?.tintColor = .systemRed
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let model = models[indexPath.row]
model.handler()
print("------------- \(indexPath.row)")
}
var mydiamondcount : Int {
return UserDefaults.standard.integer(forKey: "diamond_Count")}
func toggleHideshow() {
if UserDefaults.standard.bool(forKey: "num") {
print("-------\(UserDefaults.standard.bool(forKey: "num"))")
toggle.isEnabled = true
}
}
}
Comments
Post a Comment