实现Stripe时,必需的Init引发致命错误



我正在将Stripe添加到我的项目中。还有更多的代码,但在我开始添加Stripe和init之前,一切都正常。这是Stripe说要在他们的文档中使用的init

这是我的开始代码和初始化代码:

class BusinessOwnerVC: UIViewController, MyProtocol {
let paymentContext: STPPaymentContext

init() {
let customerContext = STPCustomerContext(keyProvider: SwiftAPI())
self.paymentContext = STPPaymentContext(customerContext: customerContext)
super.init(nibName: nil, bundle: nil)
self.paymentContext.delegate = self
self.paymentContext.hostViewController = self
self.paymentContext.paymentAmount = 5000 // This is in cents, i.e. $50 USD
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
.....

我正在使用故事板,因为我听说这很重要。当我运行代码时,会抛出致命错误并使应用程序崩溃。Stripe示例项目中有这个确切的代码,并且它很有效。

为什么我的应用程序崩溃?这个必需的init到底在做什么?我想我理解我为什么需要它,但如果你能详细说明子类所需要的之外,那将是有帮助的。

我的问题的解决方案是删除init,并且只使用所需的init,如下所示:

required init?(coder aDecoder: NSCoder) {
//fatalError("init(coder:) has not been implemented")
let customerContext = STPCustomerContext(keyProvider: SwiftAPI())
self.paymentContext = STPPaymentContext(customerContext: customerContext)
super.init(coder: aDecoder)
self.paymentContext.delegate = self
self.paymentContext.hostViewController = self
self.paymentContext.paymentAmount = 5000 // This is in cents, i.e. $50 USD
}

我留下了评论的fatelError部分,但正如你所看到的,这没有必要。就像其他人说的那样,所需的init会被故事板使用,当你在故事板类中设置数据时,你必须拥有它,就像Stripe所要求的那样。只要把super.init放在那里,你就可以出发了。

相关内容

最新更新