如何在 iOS 11 中处理应用内购买的 shouldAddStorePayment?

2024-04-11

我正在尝试实施这个新的paymentQueue(_:shouldAddStorePayment:for:) https://developer.apple.com/documentation/storekit/skpaymenttransactionobserver/2877502-paymentqueue方法,以便我的应用程序可以直接从 App Store 处理 IAP。

我正在使用itms-services://测试它的网址,就像它说的那样here https://developer.apple.com/documentation/storekit/original_api_for_in-app_purchase/testing_promoted_in-app_purchases.

问题是,我的SKPaymentTransactionObserver是一个特定的视图控制器,如果我打开时它不可见itms-services://链接委托方法将不会被调用。

对此我能做什么?我想我必须检测用户是否来自应用程序商店才能推送正确的视图控制器,但我不知道如何做。我现在能想到的唯一其他选择是使应用程序代理成为SKPaymentTransactionObserver,但这看起来真的很麻烦,当我尝试时我无法让它工作。还有其他办法吗?


这是我做的一个类,可以帮助您实现您想要的,只需复制下面的代码并将其粘贴到一个新文件中,然后您就可以简单地访问该类StoreManager.shared到您想要访问的任何方法/变量。

1- 要启动该课程,只需从您的didFinishLaunchingWithOptions StoreManager.shared.Begin()然后添加支付观察者。

import Foundation
import StoreKit


class StoreManager: NSObject{

    /**
     Initialize StoreManager and load subscriptions SKProducts from Store
     */
    static let shared = StoreManager()

    func Begin() {
        print("StoreManager initialized"))
    }

    override init() {
        super.init()

        // Add pyament observer to payment qu
        SKPaymentQueue.default().add(self)
    }

    func requestProductWithID(identifers:Set<String>){

        if SKPaymentQueue.canMakePayments() {
            let request = SKProductsRequest(productIdentifiers:
                identifers)
            request.delegate = self
            request.start()
        } else {
            print("ERROR: Store Not Available")
        }
    }

    func buyProduct(product: SKProduct) {

        print("Buying \(product.productIdentifier)...")
        let payment = SKPayment(product: product)
        SKPaymentQueue.default().add(payment)
    }

    func restorePurchases() {

        SKPaymentQueue.default().restoreCompletedTransactions()
    }
}

// MARK:
// MARK: SKProductsRequestDelegate

//The delegate receives the product information that the request was interested in.
extension StoreManager:SKProductsRequestDelegate{

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

        var products = response.products as [SKProduct]

        var buys = [SKProduct]()

        if (products.count > 0) {
            for i in 0 ..< products.count {
                let product = products[i]
                print("Product Found: ",product.localizedTitle)
            }
        } else {
            print("No products found")
        }

        let productsInvalidIds = response.invalidProductIdentifiers

        for product in productsInvalidIds {
            print("Product not found: \(product)")
        }
    }

    func request(_ request: SKRequest, didFailWithError error: Error) {
        print("Something went wrong: \(error.localizedDescription)")
    }
}

// MARK:
// MARK: SKTransactions

extension StoreManager: SKPaymentTransactionObserver {

    public func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
        for transaction in transactions {
            switch (transaction.transactionState) {
            case .purchased:
                completeTransaction(transaction: transaction)
                break
            case .failed:
                failedTransaction(transaction: transaction)
                break
            case .restored:
                restoreTransaction(transaction: transaction)
                break
            case .deferred:
                // TODO show user that is waiting for approval

                break
            case .purchasing:
                break
            }
        }
    }

    private func completeTransaction(transaction: SKPaymentTransaction) {

        print("completeTransaction...")

        deliverPurchaseForIdentifier(identifier: transaction.payment.productIdentifier)
        SKPaymentQueue.default().finishTransaction(transaction)
    }

    private func restoreTransaction(transaction: SKPaymentTransaction) {


        guard let productIdentifier = transaction.original?.payment.productIdentifier else { return }

        print("restoreTransaction... \(productIdentifier)")


        deliverPurchaseForIdentifier(identifier: productIdentifier)
        SKPaymentQueue.default().finishTransaction(transaction)
    }

    private func failedTransaction(transaction: SKPaymentTransaction) {

        if let error = transaction.error as NSError? {
            if error.domain == SKErrorDomain {
                // handle all possible errors
                switch (error.code) {
                case SKError.unknown.rawValue:
                    print("Unknown error")

                case SKError.clientInvalid.rawValue:
                    print("client is not allowed to issue the request")

                case SKError.paymentCancelled.rawValue:
                    print("user cancelled the request")

                case SKError.paymentInvalid.rawValue:
                    print("purchase identifier was invalid")

                case SKError.paymentNotAllowed.rawValue:
                    print("this device is not allowed to make the payment")

                default:
                    break;
                }
            }

        }

        SKPaymentQueue.default().finishTransaction(transaction)
    }

    private func deliverPurchaseForIdentifier(identifier: String?) {

        guard let identifier = identifier else { return }

    }
}

//In-App Purchases App Store
extension StoreManager{

    func paymentQueue(_ queue: SKPaymentQueue, shouldAddStorePayment payment: SKPayment, for product: SKProduct) -> Bool {
        return true

        //To hold
        //return false

        //And then to continue
        //SKPaymentQueue.default().add(savedPayment)
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 iOS 11 中处理应用内购买的 shouldAddStorePayment? 的相关文章

  • 故事板 - 不支持的配置 8 个冲突的约束

    我正在使用故事板自动布局 我今天在编写警告消息时注意到 MainStoryboard iphone storyboard Unsupported Configuration 8 conflicting constraints 单击警告会进入
  • 允许的 APNS 持续连接数量是多少?

    我正在尝试编写服务器端代码来为我的应用程序发送推送通知 根据 Apple 的建议 我计划保留连接并根据需要发送推送通知 Apple 还允许打开和保留多个并行连接以发送推送通知 您可以与同一网关或多个网关实例建立多个并行连接 为此 我想维护一
  • 当我从我转向的视图控制器返回时,为什么我的 UITableView 的格式完全出错了?

    我有一个UITableView使用自定义单元格 其中有一些标签可以动态决定单元格的高度 当我点击一个单元格并转到一个新的视图控制器时 返回后所有单元格的格式完全混乱 我无法弄清楚是什么导致了它 这是细胞通常的样子 我对它们设置了一些非常基本
  • 如何在 iOS 上压缩 Realm DB?

    我想定期压缩 iOS 上的 Realm 实例以回收空间 我认为该过程是将数据库复制到临时位置 然后将其复制回来并使用新的default realm 文件 我的问题是Realm 其行为就像单例并回收对象 因此我无法真正关闭它并告诉它打开新的
  • Swift 中的“funcobserveValueForKeyPath(keyPath:NSString,object:AnyObject,change:NSDictionary,context:Void)”问题

    我已经为 AVPlayer 添加了一个观察者 如下所示 self audioPlayer addObserver self forKeyPath currentItem status options NSKeyValueObservingO
  • 将第 3 方库 ZXing 导入 Xcode

    我尝试了多种方法将第 3 方库 ZXing 导入我的 iOS 应用程序 但所有方法都很痛苦 或者根本不起作用 如果有人可以建议我做错了什么 或者提出导入 ZXing 等库的更好方法 我将非常感激 一定比这个容易 这就是我所做的 结果是 My
  • 自定义字体显示在 IB 中,但不显示在模拟器中

    我已经设置了一个UITextView and a UILabel使用自定义字体 它是垂直镜像的蒙古文字体 但我还添加了英文文本 以便您可以看到效果 这些文字显示在 Interface Builder 中 但在模拟器中大部分字符都在UITex
  • 如何在IOS中的UIStackView中设置权重

    UIStackView与安卓类似LinearLayout但我不知道如何设置子视图的权重 假设我有一个垂直的UIStackView and 3 UIImageView就在里面 我想连续设置权重3 6 1UIImageViews 我怎么做 UI
  • Swift Generics 在使用继承时不会实例化泛型

    我有课Alpha and Berry class Alpha class Berry Alpha 我有一个使用继承及其泛型的函数 func myFunc
  • 使用 iPhone 中的地图视图读取当前位置名称

    我读取了当前位置的纬度和经度值 然后成功将该位置固定在 iPhone 中 现在我想使用这个纬度和经度值读取该地名 我使用以下代码来读取查找当前位置 void mapView MKMapView mapView1 didUpdateUserL
  • 如何在 iOS 9 上可靠地检测是否连接了外部键盘?

    在 iOS 9 之前 确定是否连接外部键盘的最可靠方法是监听UIKeyboardWillShowNotification并使文本字段成为第一响应者 如中所述这个问题 https stackoverflow com questions 289
  • 带操作按钮的颤动本地通知

    我在我的 flutter 项目中尝试了 flutter 本地通知插件 它在简单通知上工作正常 但我需要带有操作按钮的通知功能 请帮助我或建议我实现此功能 不幸的是 flutter local notifications 插件尚不支持操作按钮
  • 是否可以使用 Firebase 安排推送通知? [复制]

    这个问题在这里已经有答案了 我已经阅读了我能找到的所有文档 但仍然不知道这是否可行 如果我是用户 我可以安排特定时间的推送通知吗 Example 1 我是用户并打开应用程序 2 我允许通知并转到 pickerView 或其他任何内容 并设置
  • 在 Xcode 5 中重命名 iOS 项目[重复]

    这个问题在这里已经有答案了 我需要重命名一个 iOS 项目 有没有办法在不开始一个全新项目的情况下做到这一点 我发现的所有其他信息都与 Xcode 4 或旧版本相关 这些方法似乎使项目崩溃 我在尝试任何名称更改之前创建了一个快照 在 Xco
  • 更改组织以使用 Xcode 9 在 iTunes Connect 上上传二进制文件

    我在 Xcode9 上配置了多个团队 当我尝试将二进制文件上传到 Xcode 9 上的 iTunes Connect 时 没有更改团队的选项 并且出现以下错误 ERROR ITMS 4088 来自苹果开发者论坛的解决方案 1 正常存档2 窗
  • 将 SSLSetEnabledCiphers 与 AFNetworking 结合使用来禁用弱密码

    我正在尝试禁用一些密码 弱 例如单个 DES 单个 DES 40 位等 我尝试过使用这段代码在 Cocoa 中使用 CFSocket CFStream 时如何设置 SSL 密码 https stackoverflow com questio
  • 推送动画,没有阴影和停电

    我有一个简单的iOS NavigationController基于应用程序 二UICollectionViews 相继 如果元素打开 第一个合集 被点击时 第二集 将被打开 非常简单 重要的提示 Both UICollectionViews
  • AVAssetExportSession 为零 iPhone 7 - Plus 模拟器

    AVAssetExportSession在 iPhone 6 及以下版本上运行良好 但在 iPhone 7 iPhone 7 Plus 模拟器上运行不佳 Xcode 8 0 这段代码return nil在exportSession中 当在i
  • ios水平居中约束问题?

    I am having hard time in learning constraints auto layout in iOS I have used any width any height I have a storyboard sc
  • 水平 UICollectionView 单行布局

    我正在尝试使用以下命令设置简单的水平布局UICollectionView 兜圈子却没有达到预期的结果 所以任何指针或例子将不胜感激 我粘贴经常更改的代码但没有成功可能没什么意义 该图像显示两行 第一行是单个项目 尺寸正确并且在中心正确对齐

随机推荐