【问题标题】:Value of optional type 'PKPaymentAuthorizationViewController?' must be unwrapped可选类型“PKPaymentAuthorizationViewController?”的值必须拆开
【发布时间】:2019-06-07 03:31:04
【问题描述】:

当我尝试在 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'

我该如何解决这个问题?

【问题讨论】:

    标签: ios swift react-native applepay xcode10.2


    【解决方案1】:

    PKPaymentAuthorizationViewController 有一个 failable 初始化器 - 也就是说,如果用户无法付款,初始化器将返回 nil

    这意味着applePayController 是一个可选 - 它可能包含nil,所以正如错误所说,您需要在访问该属性之前解开可选; applePayController?.delegate = self。更好的方法是使用if letguard 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 可以推断类型时,无需指定类型。最好避免强制展开选项。

    【讨论】:

      猜你喜欢
      • 2022-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多