当我尝试在ApplePay的代码块下方编译适用于iOS的react-native应用
let applePayController = PKPaymentAuthorizationViewController(paymentRequest: request)
applePayController.delegate = self
let rootViewController:UIViewController? = UIApplication.shared.delegate?.window??.rootViewController!
rootViewController!.present(applePayController, animated: true, completion: nil)
抛出运行时错误。
Value of optional type 'PKPaymentAuthorizationViewController?' must be unwrapped to refer to member 'delegate' of wrapped base type 'PKPaymentAuthorizationViewController'
我该如何解决这个问题?
答案 0 :(得分:2)
PKPaymentAuthorizationViewController
具有失败的初始化程序-也就是说,如果用户无法付款,则初始化程序将返回nil
。
这意味着applePayController
是一个可选的-它可能包含nil
,因此正如错误所述,您需要先打开可选的包装,然后才能访问该属性; applePayController?.delegate = self
。更好的方法是使用if let
或guard let
。
例如:
if let applePayController = PKPaymentAuthorizationViewController(paymentRequest: request),
let rootViewController = UIApplication.shared.delegate?.window??.rootViewController {
applePayController.delegate = self
rootViewController.present(applePayController, animated: true, completion: nil)
} else {
// Payment is unavailable - handle this as appropriate
}
当Swift可以推断类型时,无需指定类型。最好也避免强制展开可选内容。