-1

When I try to compile react-native app for iOS below code block for ApplePay

    let applePayController = PKPaymentAuthorizationViewController(paymentRequest: request)
    applePayController.delegate = self
    let rootViewController:UIViewController? = UIApplication.shared.delegate?.window??.rootViewController!
    rootViewController!.present(applePayController, animated: true, completion: nil)

throwing run-time error.

Value of optional type 'PKPaymentAuthorizationViewController?' must be unwrapped to refer to member 'delegate' of wrapped base type 'PKPaymentAuthorizationViewController'

how can I solve this issue?

HM.Rajjaz
  • 369
  • 1
  • 3
  • 17

1 Answers1

2

PKPaymentAuthorizationViewController has a failable initialiser - that is, the initialiser will return nil if the user is unable to make payments.

This means that applePayController is an optional - it may contain nil, so just as the error says you need to unwrap the optional before you can access the property; applePayController?.delegate = self. A better approach is to use an if let or guard let.

For example:

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
}

There is no need to specify the type when Swift can infer it. It is also best to avoid force unwrapping optionals.

Paulw11
  • 108,386
  • 14
  • 159
  • 186