Search code examples
iosiphoneswiftuiapplepay

SwiftUI Apple Pay Button


I created this SwiftUI Apple Pay Button, it works in SwiftUI projects and it works in projects created using UIKit. The issue is when I attempt to use the ApplePayButtonRepresentable code in my work UIKit project, the ApplePayButtonRepresentable code does not compile, although it compiles and works if I create a blank project from scratch.

The errors I get include the following:

Type 'ApplePayButton.ApplePayButtonRepresentable' does not conform to protocol 'UIViewRepresentable'

I have tried to use type alias, but I still get the errors

Value of type 'Context' has no member 'coordinator'

Does anyone know of a solution?

Thanks

 extension ApplePayButton {
    struct ApplePayButtonRepresentable: UIViewRepresentable {
        var action: () -> Void
        
        func makeUIView(context: Context) -> UIView {
            context.coordinator.button
        }
        
        func updateUIView(_ rootView: UIView, context: Context) {
            context.coordinator.action = action
        }
        
        func makeCoordinator() -> Coordinator {
            Coordinator(action: action)
        }
    }
    
    final class Coordinator: NSObject {
        var action: () -> Void
        var button = PKPaymentButton(paymentButtonType: .buy, paymentButtonStyle: .black)
        
        init(action: @escaping () -> Void) {
            self.action = action
            super.init()
            
            button.addTarget(self, action: #selector(callback(_:)), for: .touchUpInside)
        }
        
        @objc
        func callback(_ sender: Any) {
            action()
        }
    }
}

Solution

  • Try replacing the UIView type in the make and update func declarations with PKPaymentButton

    I'd recommend also making the button in the Coordinator a lazy so it gets init when make is called.