我正在使用this IAP implementation guide当购买最终完成时,它会使用以下代码发布通知:
NotificationCenter.default.post(name: NSNotification.Name(rawValue: IAPHelper.IAPHelperPurchaseNotification), object: identifier)
该实现不包含观察者代码,因此我将以下代码添加到按下“购买”按钮时运行的函数中:
var functionToRun = #selector(MyViewController.runAfterBoughtFunc)
NotificationCenter.default.addObserver(self, selector: functionToRun, name: NSNotification.Name(rawValue: IAPHelper.IAPHelperPurchaseNotification), object:nil)
我的问题是,当调用NotificationCenter.default.post(...)代码时,我收到此错误:
...runAfterBoughtFuncWithNotif:]: unrecognized selector sent to instance 0x100f12fc0
(lldb)
注释
- 如果我注释掉观察者代码,我就不会再收到错误。
- 如果您查看我正在使用的 IAP 指南,就会发现评论中其他用户也遇到了同样的问题,因此这不仅仅与我的代码有关
有人知道怎么解决吗?
最佳答案
由于没有发布答案,我不得不想出一个解决办法。因此,如果您在使用观察者模式时遇到问题,可以尝试这种替代方案。
我的自定义观察者
下面的代码有一个变量来保存正在观察的事物的状态。然后,它使用计时器定期运行一个函数来检查该变量以查看状态是否发生变化。下面的例子是观察购买状态。
设置一个指向我们自定义观察者的变量,我的是 checkPurchase 状态。您很可能希望将其添加到按钮推送代码或 viewDidLoad 中,无论发生什么。
let selector = #selector(myViewController.checkPurchaseStatus)
然后设置一个定期运行该函数的计时器,在我的例子中,它将每秒运行一次“checkPurchaseStatus”。将其添加到上面的代码下。
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: selector, userInfo: nil, repeats: true)
然后设置一个变量来跟踪“状态”。如果状态将由另一个 ViewController 确定,您可以将其设为全局变量:
var purchaseState = ""
列表项
func checkPurchaseStatus () { switch purchaseState { case "": print("Waiting for purchase...") case "failed": timer.invalidate() //turns timer off purchaseState = "" //resets the variable for future uses //Add more code to be run if the purchase failed print("Purchased failed. Timer stopped.") case "succeeded": timer.invalidate() //turns timer off purchaseState = "" //resets the variable for future uses //Add more code to be run if the purchase succeeded print("Purchased succeeded. Timer stopped.") default: break } }
就是这样!它不像观察者那么强大,但在大多数情况下它是完成工作的简单、快速的方法!
关于ios - Swift 中的通知观察者错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41004491/